code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
# -*- coding: utf-8 -*- ######################################################################### ## This scaffolding model makes your app work on Google App Engine too ## File is released under public domain and you can use without limitations ######################################################################### ## if SSL/HTTPS is properly configured and you want all HTTP requests to ## be redirected to HTTPS, uncomment the line below: # request.requires_https() if not request.env.web2py_runtime_gae: ## if NOT running on Google App Engine use SQLite or other DB db = DAL('sqlite://storage.sqlite',pool_size=1,check_reserved=['all']) else: ## connect to Google BigTable (optional 'google:datastore://namespace') db = DAL('google:datastore') ## store sessions and tickets there session.connect(request, response, db=db) ## or store session in Memcache, Redis, etc. ## from gluon.contrib.memdb import MEMDB ## from google.appengine.api.memcache import Client ## session.connect(request, response, db = MEMDB(Client())) ## by default give a view/generic.extension to all actions from localhost ## none otherwise. a pattern can be 'controller/function.extension' response.generic_patterns = ['*'] if request.is_local else [] ## (optional) optimize handling of static files # response.optimize_css = 'concat,minify,inline' # response.optimize_js = 'concat,minify,inline' ######################################################################### ## Here is sample code if you need for ## - email capabilities ## - authentication (registration, login, logout, ... ) ## - authorization (role based authorization) ## - services (xml, csv, json, xmlrpc, jsonrpc, amf, rss) ## - old style crud actions ## (more options discussed in gluon/tools.py) ######################################################################### from gluon.tools import Auth, Crud, Service, PluginManager, prettydate auth = Auth(db) crud, service, plugins = Crud(db), Service(), PluginManager() ## create all tables needed by auth if not custom tables auth.define_tables(username=False, signature=False) ## configure email mail = auth.settings.mailer mail.settings.server = 'logging' or 'smtp.gmail.com:587' mail.settings.sender = 'you@gmail.com' mail.settings.login = 'username:password' ## configure auth policy auth.settings.registration_requires_verification = False auth.settings.registration_requires_approval = False auth.settings.reset_password_requires_verification = True ## if you need to use OpenID, Facebook, MySpace, Twitter, Linkedin, etc. ## register with janrain.com, write your domain:api_key in private/janrain.key from gluon.contrib.login_methods.rpx_account import use_janrain use_janrain(auth, filename='private/janrain.key') ######################################################################### ## Define your tables below (or better in another model file) for example ## ## >>> db.define_table('mytable',Field('myfield','string')) ## ## Fields can be 'string','text','password','integer','double','boolean' ## 'date','time','datetime','blob','upload', 'reference TABLENAME' ## There is an implicit 'id integer autoincrement' field ## Consult manual for more options, validators, etc. ## ## More API examples for controllers: ## ## >>> db.mytable.insert(myfield='value') ## >>> rows=db(db.mytable.myfield=='value').select(db.mytable.ALL) ## >>> for row in rows: print row.id, row.myfield ######################################################################### ## after defining tables, uncomment below to enable auditing # auth.enable_record_versioning(db)
11ghenrylv-mongotest
applications/welcome/models/db.py
Python
lgpl
3,619
# -*- coding: utf-8 -*- # ########################################################## # ## make sure administrator is on localhost # ########################################################### import os import socket import datetime import copy import gluon.contenttype import gluon.fileutils try: import pygraphviz as pgv except ImportError: pgv = None response.subtitle = 'Database Administration (appadmin)' # ## critical --- make a copy of the environment global_env = copy.copy(globals()) global_env['datetime'] = datetime http_host = request.env.http_host.split(':')[0] remote_addr = request.env.remote_addr try: hosts = (http_host, socket.gethostname(), socket.gethostbyname(http_host), '::1', '127.0.0.1', '::ffff:127.0.0.1') except: hosts = (http_host, ) if request.env.http_x_forwarded_for or request.is_https: session.secure() elif (remote_addr not in hosts) and (remote_addr != "127.0.0.1"): raise HTTP(200, T('appadmin is disabled because insecure channel')) if (request.application == 'admin' and not session.authorized) or \ (request.application != 'admin' and not gluon.fileutils.check_credentials(request)): redirect(URL('admin', 'default', 'index', vars=dict(send=URL(args=request.args, vars=request.vars)))) ignore_rw = True response.view = 'appadmin.html' response.menu = [[T('design'), False, URL('admin', 'default', 'design', args=[request.application])], [T('db'), False, URL('index')], [T('state'), False, URL('state')], [T('cache'), False, URL('ccache')]] # ########################################################## # ## auxiliary functions # ########################################################### if False and request.tickets_db: from gluon.restricted import TicketStorage ts = TicketStorage() ts._get_table(request.tickets_db, ts.tablename, request.application) def get_databases(request): dbs = {} for (key, value) in global_env.items(): cond = False try: cond = isinstance(value, GQLDB) except: cond = isinstance(value, SQLDB) if cond: dbs[key] = value return dbs databases = get_databases(None) def eval_in_global_env(text): exec ('_ret=%s' % text, {}, global_env) return global_env['_ret'] def get_database(request): if request.args and request.args[0] in databases: return eval_in_global_env(request.args[0]) else: session.flash = T('invalid request') redirect(URL('index')) def get_table(request): db = get_database(request) if len(request.args) > 1 and request.args[1] in db.tables: return (db, request.args[1]) else: session.flash = T('invalid request') redirect(URL('index')) def get_query(request): try: return eval_in_global_env(request.vars.query) except Exception: return None def query_by_table_type(tablename, db, request=request): keyed = hasattr(db[tablename], '_primarykey') if keyed: firstkey = db[tablename][db[tablename]._primarykey[0]] cond = '>0' if firstkey.type in ['string', 'text']: cond = '!=""' qry = '%s.%s.%s%s' % ( request.args[0], request.args[1], firstkey.name, cond) else: qry = '%s.%s.id>0' % tuple(request.args[:2]) return qry # ########################################################## # ## list all databases and tables # ########################################################### def index(): return dict(databases=databases) # ########################################################## # ## insert a new record # ########################################################### def insert(): (db, table) = get_table(request) form = SQLFORM(db[table], ignore_rw=ignore_rw) if form.accepts(request.vars, session): response.flash = T('new record inserted') return dict(form=form, table=db[table]) # ########################################################## # ## list all records in table and insert new record # ########################################################### def download(): import os db = get_database(request) return response.download(request, db) def csv(): import gluon.contenttype response.headers['Content-Type'] = \ gluon.contenttype.contenttype('.csv') db = get_database(request) query = get_query(request) if not query: return None response.headers['Content-disposition'] = 'attachment; filename=%s_%s.csv'\ % tuple(request.vars.query.split('.')[:2]) return str(db(query, ignore_common_filters=True).select()) def import_csv(table, file): table.import_from_csv_file(file) def select(): import re db = get_database(request) dbname = request.args[0] regex = re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>\d+)') if len(request.args) > 1 and hasattr(db[request.args[1]], '_primarykey'): regex = re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>.+)') if request.vars.query: match = regex.match(request.vars.query) if match: request.vars.query = '%s.%s.%s==%s' % (request.args[0], match.group('table'), match.group('field'), match.group('value')) else: request.vars.query = session.last_query query = get_query(request) if request.vars.start: start = int(request.vars.start) else: start = 0 nrows = 0 stop = start + 100 table = None rows = [] orderby = request.vars.orderby if orderby: orderby = dbname + '.' + orderby if orderby == session.last_orderby: if orderby[0] == '~': orderby = orderby[1:] else: orderby = '~' + orderby session.last_orderby = orderby session.last_query = request.vars.query form = FORM(TABLE(TR(T('Query:'), '', INPUT(_style='width:400px', _name='query', _value=request.vars.query or '', requires=IS_NOT_EMPTY( error_message=T("Cannot be empty")))), TR(T('Update:'), INPUT(_name='update_check', _type='checkbox', value=False), INPUT(_style='width:400px', _name='update_fields', _value=request.vars.update_fields or '')), TR(T('Delete:'), INPUT(_name='delete_check', _class='delete', _type='checkbox', value=False), ''), TR('', '', INPUT(_type='submit', _value=T('submit')))), _action=URL(r=request, args=request.args)) tb = None if form.accepts(request.vars, formname=None): regex = re.compile(request.args[0] + '\.(?P<table>\w+)\..+') match = regex.match(form.vars.query.strip()) if match: table = match.group('table') try: nrows = db(query).count() if form.vars.update_check and form.vars.update_fields: db(query).update(**eval_in_global_env('dict(%s)' % form.vars.update_fields)) response.flash = T('%s %%{row} updated', nrows) elif form.vars.delete_check: db(query).delete() response.flash = T('%s %%{row} deleted', nrows) nrows = db(query).count() if orderby: rows = db(query, ignore_common_filters=True).select(limitby=( start, stop), orderby=eval_in_global_env(orderby)) else: rows = db(query, ignore_common_filters=True).select( limitby=(start, stop)) except Exception, e: import traceback tb = traceback.format_exc() (rows, nrows) = ([], 0) response.flash = DIV(T('Invalid Query'), PRE(str(e))) # begin handle upload csv csv_table = table or request.vars.table if csv_table: formcsv = FORM(str(T('or import from csv file')) + " ", INPUT(_type='file', _name='csvfile'), INPUT(_type='hidden', _value=csv_table, _name='table'), INPUT(_type='submit', _value=T('import'))) else: formcsv = None if formcsv and formcsv.process().accepted: try: import_csv(db[request.vars.table], request.vars.csvfile.file) response.flash = T('data uploaded') except Exception, e: response.flash = DIV(T('unable to parse csv file'), PRE(str(e))) # end handle upload csv return dict( form=form, table=table, start=start, stop=stop, nrows=nrows, rows=rows, query=request.vars.query, formcsv=formcsv, tb=tb, ) # ########################################################## # ## edit delete one record # ########################################################### def update(): (db, table) = get_table(request) keyed = hasattr(db[table], '_primarykey') record = None db[table]._common_filter = None if keyed: key = [f for f in request.vars if f in db[table]._primarykey] if key: record = db(db[table][key[0]] == request.vars[key[ 0]]).select().first() else: record = db(db[table].id == request.args( 2)).select().first() if not record: qry = query_by_table_type(table, db) session.flash = T('record does not exist') redirect(URL('select', args=request.args[:1], vars=dict(query=qry))) if keyed: for k in db[table]._primarykey: db[table][k].writable = False form = SQLFORM( db[table], record, deletable=True, delete_label=T('Check to delete'), ignore_rw=ignore_rw and not keyed, linkto=URL('select', args=request.args[:1]), upload=URL(r=request, f='download', args=request.args[:1])) if form.accepts(request.vars, session): session.flash = T('done!') qry = query_by_table_type(table, db) redirect(URL('select', args=request.args[:1], vars=dict(query=qry))) return dict(form=form, table=db[table]) # ########################################################## # ## get global variables # ########################################################### def state(): return dict() def ccache(): cache.ram.initialize() cache.disk.initialize() form = FORM( P(TAG.BUTTON( T("Clear CACHE?"), _type="submit", _name="yes", _value="yes")), P(TAG.BUTTON( T("Clear RAM"), _type="submit", _name="ram", _value="ram")), P(TAG.BUTTON( T("Clear DISK"), _type="submit", _name="disk", _value="disk")), ) if form.accepts(request.vars, session): clear_ram = False clear_disk = False session.flash = "" if request.vars.yes: clear_ram = clear_disk = True if request.vars.ram: clear_ram = True if request.vars.disk: clear_disk = True if clear_ram: cache.ram.clear() session.flash += T("Ram Cleared") if clear_disk: cache.disk.clear() session.flash += T("Disk Cleared") redirect(URL(r=request)) try: from guppy import hpy hp = hpy() except ImportError: hp = False import shelve import os import copy import time import math from gluon import portalocker ram = { 'entries': 0, 'bytes': 0, 'objects': 0, 'hits': 0, 'misses': 0, 'ratio': 0, 'oldest': time.time(), 'keys': [] } disk = copy.copy(ram) total = copy.copy(ram) disk['keys'] = [] total['keys'] = [] def GetInHMS(seconds): hours = math.floor(seconds / 3600) seconds -= hours * 3600 minutes = math.floor(seconds / 60) seconds -= minutes * 60 seconds = math.floor(seconds) return (hours, minutes, seconds) for key, value in cache.ram.storage.iteritems(): if isinstance(value, dict): ram['hits'] = value['hit_total'] - value['misses'] ram['misses'] = value['misses'] try: ram['ratio'] = ram['hits'] * 100 / value['hit_total'] except (KeyError, ZeroDivisionError): ram['ratio'] = 0 else: if hp: ram['bytes'] += hp.iso(value[1]).size ram['objects'] += hp.iso(value[1]).count ram['entries'] += 1 if value[0] < ram['oldest']: ram['oldest'] = value[0] ram['keys'].append((key, GetInHMS(time.time() - value[0]))) folder = os.path.join(request.folder,'cache') if not os.path.exists(folder): os.mkdir(folder) locker = open(os.path.join(folder, 'cache.lock'), 'a') portalocker.lock(locker, portalocker.LOCK_EX) disk_storage = shelve.open( os.path.join(folder, 'cache.shelve')) try: for key, value in disk_storage.items(): if isinstance(value, dict): disk['hits'] = value['hit_total'] - value['misses'] disk['misses'] = value['misses'] try: disk['ratio'] = disk['hits'] * 100 / value['hit_total'] except (KeyError, ZeroDivisionError): disk['ratio'] = 0 else: if hp: disk['bytes'] += hp.iso(value[1]).size disk['objects'] += hp.iso(value[1]).count disk['entries'] += 1 if value[0] < disk['oldest']: disk['oldest'] = value[0] disk['keys'].append((key, GetInHMS(time.time() - value[0]))) finally: portalocker.unlock(locker) locker.close() disk_storage.close() total['entries'] = ram['entries'] + disk['entries'] total['bytes'] = ram['bytes'] + disk['bytes'] total['objects'] = ram['objects'] + disk['objects'] total['hits'] = ram['hits'] + disk['hits'] total['misses'] = ram['misses'] + disk['misses'] total['keys'] = ram['keys'] + disk['keys'] try: total['ratio'] = total['hits'] * 100 / (total['hits'] + total['misses']) except (KeyError, ZeroDivisionError): total['ratio'] = 0 if disk['oldest'] < ram['oldest']: total['oldest'] = disk['oldest'] else: total['oldest'] = ram['oldest'] ram['oldest'] = GetInHMS(time.time() - ram['oldest']) disk['oldest'] = GetInHMS(time.time() - disk['oldest']) total['oldest'] = GetInHMS(time.time() - total['oldest']) def key_table(keys): return TABLE( TR(TD(B(T('Key'))), TD(B(T('Time in Cache (h:m:s)')))), *[TR(TD(k[0]), TD('%02d:%02d:%02d' % k[1])) for k in keys], **dict(_class='cache-keys', _style="border-collapse: separate; border-spacing: .5em;")) ram['keys'] = key_table(ram['keys']) disk['keys'] = key_table(disk['keys']) total['keys'] = key_table(total['keys']) return dict(form=form, total=total, ram=ram, disk=disk, object_stats=hp != False) def table_template(table): from gluon.html import TR, TD, TABLE, TAG def FONT(*args, **kwargs): return TAG.font(*args, **kwargs) def types(field): f_type = field.type if not isinstance(f_type,str): return ' ' elif f_type == 'string': return field.length elif f_type == 'id': return B('pk') elif f_type.startswith('reference') or \ f_type.startswith('list:reference'): return B('fk') else: return ' ' # This is horribe HTML but the only one graphiz understands rows = [] cellpadding = 4 color = "#000000" bgcolor = "#FFFFFF" face = "Helvetica" face_bold = "Helvetica Bold" border = 0 rows.append(TR(TD(FONT(table, _face=face_bold, _color=bgcolor), _colspan=3, _cellpadding=cellpadding, _align="center", _bgcolor=color))) for row in db[table]: rows.append(TR(TD(FONT(row.name, _color=color, _face=face_bold), _align="left", _cellpadding=cellpadding, _border=border), TD(FONT(row.type, _color=color, _face=face), _align="left", _cellpadding=cellpadding, _border=border), TD(FONT(types(row), _color=color, _face=face), _align="center", _cellpadding=cellpadding, _border=border))) return "< %s >" % TABLE(*rows, **dict(_bgcolor=bgcolor, _border=1, _cellborder=0, _cellspacing=0) ).xml() def bg_graph_model(): graph = pgv.AGraph(layout='dot', directed=True, strict=False, rankdir='LR') subgraphs = dict() for tablename in db.tables: if hasattr(db[tablename],'_meta_graphmodel'): meta_graphmodel = db[tablename]._meta_graphmodel else: meta_graphmodel = dict(group='Undefined', color='#ECECEC') group = meta_graphmodel['group'].replace(' ', '') if not subgraphs.has_key(group): subgraphs[group] = dict(meta=meta_graphmodel, tables=[]) subgraphs[group]['tables'].append(tablename) else: subgraphs[group]['tables'].append(tablename) graph.add_node(tablename, name=tablename, shape='plaintext', label=table_template(tablename)) for n, key in enumerate(subgraphs.iterkeys()): graph.subgraph(nbunch=subgraphs[key]['tables'], name='cluster%d' % n, style='filled', color=subgraphs[key]['meta']['color'], label=subgraphs[key]['meta']['group']) for tablename in db.tables: for field in db[tablename]: f_type = field.type if isinstance(f_type,str) and ( f_type.startswith('reference') or f_type.startswith('list:reference')): referenced_table = f_type.split()[1].split('.')[0] n1 = graph.get_node(tablename) n2 = graph.get_node(referenced_table) graph.add_edge(n1, n2, color="#4C4C4C", label='') graph.layout() #return graph.draw(format='png', prog='dot') if not request.args: return graph.draw(format='png', prog='dot') else: response.headers['Content-Disposition']='attachment;filename=graph.%s'%request.args(0) if request.args(0) == 'dot': return graph.string() else: return graph.draw(format=request.args(0), prog='dot') def graph_model(): return dict(databases=databases, pgv=pgv)
11ghenrylv-mongotest
applications/welcome/controllers/appadmin.py
Python
lgpl
19,472
# -*- coding: utf-8 -*- # this file is released under public domain and you can use without limitations ######################################################################### ## This is a sample controller ## - index is the default action of any application ## - user is required for authentication and authorization ## - download is for downloading files uploaded in the db (does streaming) ## - call exposes all registered services (none by default) ######################################################################### def index(): """ example action using the internationalization operator T and flash rendered by views/default/index.html or views/generic.html if you need a simple wiki simple replace the two lines below with: return auth.wiki() """ response.flash = T("Welcome to web2py!") return dict(message=T('Hello World')) def user(): """ exposes: http://..../[app]/default/user/login http://..../[app]/default/user/logout http://..../[app]/default/user/register http://..../[app]/default/user/profile http://..../[app]/default/user/retrieve_password http://..../[app]/default/user/change_password use @auth.requires_login() @auth.requires_membership('group name') @auth.requires_permission('read','table name',record_id) to decorate functions that need access control """ return dict(form=auth()) @cache.action() def download(): """ allows downloading of uploaded files http://..../[app]/default/download/[filename] """ return response.download(request, db) def call(): """ exposes services. for example: http://..../[app]/default/call/jsonrpc decorate with @services.jsonrpc the functions to expose supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv """ return service() @auth.requires_signature() def data(): """ http://..../[app]/default/data/tables http://..../[app]/default/data/create/[table] http://..../[app]/default/data/read/[table]/[id] http://..../[app]/default/data/update/[table]/[id] http://..../[app]/default/data/delete/[table]/[id] http://..../[app]/default/data/select/[table] http://..../[app]/default/data/search/[table] but URLs must be signed, i.e. linked with A('table',_href=URL('data/tables',user_signature=True)) or with the signed load operator LOAD('default','data.load',args='tables',ajax=True,user_signature=True) """ return dict(form=crud())
11ghenrylv-mongotest
applications/welcome/controllers/default.py
Python
lgpl
2,512
# -*- coding: utf-8 -*- # This is an app-specific example router # # This simple router is used for setting languages from app/languages directory # as a part of the application path: app/<lang>/controller/function # Language from default.py or 'en' (if the file is not found) is used as # a default_language # # See <web2py-root-dir>/router.example.py for parameter's detail #------------------------------------------------------------------------------------- # To enable this route file you must do the steps: # # 1. rename <web2py-root-dir>/router.example.py to routes.py # 2. rename this APP/routes.example.py to APP/routes.py # (where APP - is your application directory) # 3. restart web2py (or reload routes in web2py admin interfase) # # YOU CAN COPY THIS FILE TO ANY APLLICATION'S ROOT DIRECTORY WITHOUT CHANGES! from fileutils import abspath from languages import read_possible_languages possible_languages = read_possible_languages(abspath('applications', app)) #NOTE! app - is an application based router's parameter with name of an # application. E.g.'welcome' routers = { app: dict( default_language = possible_languages['default'][0], languages = [lang for lang in possible_languages if lang != 'default'] ) } #NOTE! To change language in your application using these rules add this line #in one of your models files: # if request.uri_language: T.force(request.uri_language)
11ghenrylv-mongotest
applications/welcome/routes.example.py
Python
lgpl
1,470
#!/usr/bin/env python from setuptools import setup from gluon.fileutils import tar, untar, read_file, write_file import tarfile import sys def tar(file, filelist, expression='^.+$'): """ tars dir/files into file, only tars file that match expression """ tar = tarfile.TarFile(file, 'w') try: for element in filelist: try: for file in listdir(element, expression, add_dirs=True): tar.add(os.path.join(element, file), file, False) except: tar.add(element) finally: tar.close() def start(): if 'sdist' in sys.argv: tar('gluon/env.tar', ['applications', 'VERSION', 'splashlogo.gif']) setup(name='web2py', version=read_file("VERSION").split()[1], description="""full-stack framework for rapid development and prototyping of secure database-driven web-based applications, written and programmable in Python.""", long_description=""" Everything in one package with no dependencies. Development, deployment, debugging, testing, database administration and maintenance of applications can be done via the provided web interface. web2py has no configuration files, requires no installation, can run off a USB drive. web2py uses Python for the Model, the Views and the Controllers, has a built-in ticketing system to manage errors, an internationalization engine, works with SQLite, PostgreSQL, MySQL, MSSQL, FireBird, Oracle, IBM DB2, Informix, Ingres, sybase and Google App Engine via a Database Abstraction Layer. web2py includes libraries to handle HTML/XML, RSS, ATOM, CSV, RTF, JSON, AJAX, XMLRPC, WIKI markup. Production ready, capable of upload/download streaming of very large files, and always backward compatible. """, author='Massimo Di Pierro', author_email='mdipierro@cs.depaul.edu', license='http://web2py.com/examples/default/license', classifiers=["Development Status :: 5 - Production/Stable"], url='http://web2py.com', platforms='Windows, Linux, Mac, Unix,Windows Mobile', packages=['gluon', 'gluon/contrib', 'gluon/contrib/gateways', 'gluon/contrib/login_methods', 'gluon/contrib/markdown', 'gluon/contrib/markmin', 'gluon/contrib/memcache', 'gluon/contrib/fpdf', 'gluon/contrib/pymysql', 'gluon/contrib/pyrtf', 'gluon/contrib/pysimplesoap', 'gluon/contrib/simplejson', 'gluon/tests', ], package_data={'gluon': ['env.tar']}, scripts=['w2p_apps', 'w2p_run', 'w2p_clone'], ) if __name__ == '__main__': #print "web2py does not require installation and" #print "you should just start it with:" #print #print "$ python web2py.py" #print #print "are you sure you want to install it anyway (y/n)?" #s = raw_input('>') #if s.lower()[:1]=='y': start()
11ghenrylv-mongotest
setup.py
Python
lgpl
3,230
""" web2py handler for isapi-wsgi for IIS. Requires: http://code.google.com/p/isapi-wsgi/ """ # The entry point for the ISAPI extension. def __ExtensionFactory__(): import os import sys path = os.path.dirname(os.path.abspath(__file__)) os.chdir(path) sys.path = [path] + [p for p in sys.path if not p == path] import gluon.main import isapi_wsgi application = gluon.main.wsgibase return isapi_wsgi.ISAPIThreadPoolHandler(application) # ISAPI installation: if __name__ == '__main__': import sys if len(sys.argv) < 2: print "USAGE: python isapiwsgihandler.py install --server=Sitename" sys.exit(0) from isapi.install import ISAPIParameters from isapi.install import ScriptMapParams from isapi.install import VirtualDirParameters from isapi.install import HandleCommandLine params = ISAPIParameters() sm = [ScriptMapParams(Extension="*", Flags=0)] vd = VirtualDirParameters(Name="appname", Description="Web2py in Python", ScriptMaps=sm, ScriptMapUpdate="replace") params.VirtualDirs = [vd] HandleCommandLine(params)
11ghenrylv-mongotest
isapiwsgihandler.py
Python
lgpl
1,203
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) This is a CGI handler for Apache Requires apache+[mod_cgi or mod_cgid]. In httpd.conf put something like: LoadModule cgi_module modules/mod_cgi.so ScriptAlias / /path/to/cgihandler.py/ Example of httpd.conf ------------ <VirtualHost *:80> ServerName web2py.example.com ScriptAlias / /users/www-data/web2py/cgihandler.py/ <Directory /users/www-data/web2py> AllowOverride None Order Allow,Deny Deny from all <Files cgihandler.py> Allow from all </Files> </Directory> AliasMatch ^/([^/]+)/static/(.*) \ /users/www-data/web2py/applications/$1/static/$2 <Directory /users/www-data/web2py/applications/*/static/> Order Allow,Deny Allow from all </Directory> <Location /admin> Deny from all </Location> <LocationMatch ^/([^/]+)/appadmin> Deny from all </LocationMatch> CustomLog /private/var/log/apache2/access.log common ErrorLog /private/var/log/apache2/error.log </VirtualHost> ---------------------------------- """ import os import sys import wsgiref.handlers path = os.path.dirname(os.path.abspath(__file__)) os.chdir(path) sys.path = [path] + [p for p in sys.path if not p == path] import gluon.main wsgiref.handlers.CGIHandler().run(gluon.main.wsgibase)
11ghenrylv-mongotest
cgihandler.py
Python
lgpl
1,464
:: run from web2py root folder because of autodoc & web2py import behaviour!!!! sphinx-build -b html -w doc\sphinx-build.log -Ea doc/source applications/examples/static/sphinx ::sphinx-build -b html -w sphinx-build.log -Ea source ../applications/examples/static/sphinx
11ghenrylv-mongotest
doc/make-doc_html.bat
Batchfile
lgpl
269
# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source .PHONY: help clean html dirhtml pickle json htmlhelp qthelp latex changes linkcheck doctest help: @echo "Please use \`make <target>' where <target> is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf build/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) build/html @echo @echo "Build finished. The HTML pages are in build/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) build/dirhtml @echo @echo "Build finished. The HTML pages are in build/dirhtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) build/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) build/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) build/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in build/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) build/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in build/qthelp, like this:" @echo "# qcollectiongenerator build/qthelp/Web2Py.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile build/qthelp/Web2Py.qhc" latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) build/latex @echo @echo "Build finished; the LaTeX files are in build/latex." @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \ "run these through (pdf)latex." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) build/changes @echo @echo "The overview file is in build/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) build/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in build/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) build/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in build/doctest/output.txt."
11ghenrylv-mongotest
doc/Makefile
Makefile
lgpl
3,064
#!/usr/bin/env python # -*- coding: utf-8 -*- # Sropulpof # Copyright (C) 2008 Société des arts technologiques (SAT) # http://www.sat.qc.ca # All rights reserved. # # This file 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. # # Sropulpof 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 Sropulpof. If not, see <http:#www.gnu.org/licenses/>. """ This script parse a directory tree looking for python modules and packages and create ReST files appropriately to create code documentation with Sphinx. It also create a modules index. """ import os import optparse # automodule options options = ['members', 'undoc-members', # 'inherited-members', # disable because there's a bug in sphinx 'show-inheritance'] def create_file_name(base, opts): """Create file name from base name, path and suffix""" return os.path.join(opts.destdir, "%s.%s" % (base, opts.suffix)) def write_directive(module): """Create the automodule directive and add the options""" directive = '.. automodule:: %s\n' % module for option in options: directive += ' :%s:\n' % option return directive def write_heading(module, kind='Module'): """Create the page heading.""" module = module.title() heading = title_line(module + ' Documentation', '=') heading += 'This page contains the %s %s documentation.\n\n' % (module, kind) return heading def write_sub(module, kind='Module'): """Create the module subtitle""" sub = title_line('The :mod:`%s` %s' % (module, kind), '-') return sub def title_line(title, char): """ Underline the title with the character pass, with the right length.""" return '%s\n%s\n\n' % (title, len(title) * char) def create_module_file(root, module, opts): """Build the text of the file and write the file.""" name = create_file_name(module, opts) if not opts.force and os.path.isfile(name): print 'File %s already exists.' % name elif check_for_code('%s/%s.py' % (root, module)): # don't build the file if there's no code in it print 'Creating file %s for module.' % name text = write_heading(module) text += write_sub(module) text += write_directive(module) # write the file if not opts.dryrun: fd = open(name, 'w') fd.write(text) fd.close() def create_package_file(root, subroot, py_files, opts, subs=None): """Build the text of the file and write the file.""" package = root.rpartition('/')[2].lower() name = create_file_name(subroot, opts) if not opts.force and os.path.isfile(name): print 'File %s already exists.' % name else: print 'Creating file %s for package.' % name text = write_heading(package, 'Package') if subs == None: subs = [] else: # build a list of directories that are package (they contain an __init_.py file) subs = [sub for sub in subs if os.path.isfile('%s/%s/__init__.py' % (root, sub))] # if there's some package directories, add a TOC for theses subpackages if subs: text += title_line('Subpackages', '-') text += '.. toctree::\n\n' for sub in subs: text += ' %s.%s\n' % (subroot, sub) text += '\n' # add each package's module for py_file in py_files: if not check_for_code('%s/%s' % (root, py_file)): # don't build the file if there's no code in it continue py_file = py_file[:-3] py_path = '%s.%s' % (subroot, py_file) kind = "Module" if py_file == '__init__': kind = "Package" text += write_sub(kind == 'Package' and package or py_file, kind) text += write_directive(kind == "Package" and subroot or py_path) text += '\n' # write the file if not opts.dryrun: fd = open(name, 'w') fd.write(text) fd.close() def check_for_code(module): """ Check if there's at least one class or one function in the module. """ fd = open(module, 'r') for line in fd: if line.startswith('def ') or line.startswith('class '): fd.close() return True fd.close() return False def recurse_tree(path, excludes, opts): """ Look for every file in the directory tree and create the corresponding ReST files. """ toc = [] excludes = format_excludes(path, excludes) tree = os.walk(path, False) for root, subs, files in tree: # keep only the Python script files py_files = check_py_file(files) # remove hidden ('.') and private ('_') directories subs = [sub for sub in subs if sub[0] not in ['.', '_']] # check if there's valid files to process if "/." in root or "/_" in root \ or not py_files \ or check_excludes(root, excludes): continue subroot = root[len(path):].lstrip('/').replace('/', '.') if root == path: # we are at the root level so we create only modules for py_file in py_files: module = py_file[:-3] create_module_file(root, module, opts) toc.append(module) elif not subs and "__init__.py" in py_files: # we are in a package without sub package create_package_file(root, subroot, py_files, opts=opts) toc.append(subroot) elif "__init__.py" in py_files: # we are in package with subpackage(s) create_package_file(root, subroot, py_files, opts, subs) toc.append(subroot) # create the module's index if not opts.notoc: modules_toc(toc, opts) def modules_toc(modules, opts, name='modules'): """ Create the module's index. """ fname = create_file_name(name, opts) if not opts.force and os.path.exists(fname): print "File %s already exists." % name return print "Creating module's index modules.txt." text = write_heading(opts.header, 'Modules') text += title_line('Modules:', '-') text += '.. toctree::\n' text += ' :maxdepth: %s\n\n' % opts.maxdepth modules.sort() prev_module = '' for module in modules: # look if the module is a subpackage and, if yes, ignore it if module.startswith(prev_module + '.'): continue prev_module = module text += ' %s\n' % module # write the file if not opts.dryrun: fd = open(fname, 'w') fd.write(text) fd.close() def format_excludes(path, excludes): """ Format the excluded directory list. (verify that the path is not from the root of the volume or the root of the package) """ f_excludes = [] for exclude in excludes: if exclude[0] != '/' and exclude[:len(path)] != path: exclude = '%s/%s' % (path, exclude) # remove trailing slash f_excludes.append(exclude.rstrip('/')) return f_excludes def check_excludes(root, excludes): """ Check if the directory is in the exclude list. """ for exclude in excludes: if root[:len(exclude)] == exclude: return True return False def check_py_file(files): """ Return a list with only the python scripts (remove all other files). """ py_files = [fich for fich in files if fich[-3:] == '.py'] return py_files if __name__ == '__main__': parser = optparse.OptionParser(usage="""usage: %prog [options] <package path> [exclude paths, ...] Note: By default this script will not overwrite already created files.""") parser.add_option("-n", "--doc-header", action="store", dest="header", help="Documentation Header (default=Project)", default="Project") parser.add_option("-d", "--dest-dir", action="store", dest="destdir", help="Output destination directory", default="") parser.add_option("-s", "--suffix", action="store", dest="suffix", help="module suffix (default=txt)", default="txt") parser.add_option("-m", "--maxdepth", action="store", dest="maxdepth", help="Maximum depth of submodules to show in the TOC (default=4)", type="int", default=4) parser.add_option("-r", "--dry-run", action="store_true", dest="dryrun", help="Run the script without creating the files") parser.add_option("-f", "--force", action="store_true", dest="force", help="Overwrite all the files") parser.add_option("-t", "--no-toc", action="store_true", dest="notoc", help="Don't create the table of content file") (opts, args) = parser.parse_args() if len(args) < 1: parser.error("package path is required.") else: if os.path.isdir(args[0]): # if there's some exclude arguments, build the list of excludes excludes = args[1:] recurse_tree(args[0], excludes, opts) else: print '%s is not a valid directory.' % args
11ghenrylv-mongotest
doc/generate_modules.py
Python
lgpl
9,629
"""Convert a FAQ (AlterEgo) markdown dump into ReSt documents using pandoc **Todo** #. add titles #. add logging #. add CLI with optparse """ import os import sys import glob import subprocess import logging indir = 'faq_markdown' outdir = 'faq_rst' inpath = os.path.join('.', indir) outpath = os.path.join('.', outdir) pattern = inpath + '/*.txt' out_ext = 'rst' for file in glob.glob(pattern): infile = file file_basename = os.path.basename(file) outfile_name = os.path.splitext(file_basename)[0] + '.' + out_ext outfile = os.path.join(outpath, outfile_name) # pandoc -s -w rst --toc README -o example6.text logging.info("converting file %s to format <%s>" % (file_basename, out_ext)) convert_call = ["pandoc", "-s", "-w", out_ext, infile, "-o", outfile ] p = subprocess.call(convert_call) logging.info("Finshed!")
11ghenrylv-mongotest
doc/convert_faq.py
Python
lgpl
983
@ECHO OFF REM Command file for Sphinx documentation set SPHINXBUILD=sphinx-build set ALLSPHINXOPTS=-d build/doctrees %SPHINXOPTS% source if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^<target^>` where ^<target^> is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. changes to make an overview over all changed/added/deprecated items echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (build\*) do rmdir /q /s %%i del /q /s build\* goto end ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% build/html echo. echo.Build finished. The HTML pages are in build/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% build/dirhtml echo. echo.Build finished. The HTML pages are in build/dirhtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% build/pickle echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% build/json echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% build/htmlhelp echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in build/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% build/qthelp echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in build/qthelp, like this: echo.^> qcollectiongenerator build\qthelp\Web2Py.qhcp echo.To view the help file: echo.^> assistant -collectionFile build\qthelp\Web2Py.ghc goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% build/latex echo. echo.Build finished; the LaTeX files are in build/latex. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% build/changes echo. echo.The overview file is in build/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% build/linkcheck echo. echo.Link check complete; look for any errors in the above output ^ or in build/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% build/doctest echo. echo.Testing of doctests in the sources finished, look at the ^ results in build/doctest/output.txt. goto end ) :end
11ghenrylv-mongotest
doc/make.bat
Batchfile
lgpl
3,053
#!/usr/bin/env python # -*- coding: utf-8 -*- # Sropulpof # Copyright (C) 2008 Société des arts technologiques (SAT) # http://www.sat.qc.ca # All rights reserved. # # This file 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. # # Sropulpof 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 Sropulpof. If not, see <http:#www.gnu.org/licenses/>. """ This script parse a directory tree looking for python modules and packages and create ReST files appropriately to create code documentation with Sphinx. It also create a modules index. """ import os import optparse # automodule options options = ['members', 'undoc-members', # 'inherited-members', # disable because there's a bug in sphinx 'show-inheritance'] def create_file_name(base, opts): """Create file name from base name, path and suffix""" return os.path.join(opts.destdir, "%s.%s" % (base, opts.suffix)) def write_directive(package, module): """Create the automodule directive and add the options""" directive = '.. automodule:: %s.%s\n' % (package, module) for option in options: directive += ' :%s:\n' % option return directive def write_heading(module, kind='Module'): """Create the page heading.""" module = module.title() heading = title_line(module + ' Documentation', '=') heading += 'This page contains the %s %s documentation.\n\n' % (module, kind) return heading def write_sub(module, kind='Module'): """Create the module subtitle""" sub = title_line('The :mod:`%s` %s' % (module, kind), '-') return sub def title_line(title, char): """ Underline the title with the character pass, with the right length.""" return '%s\n%s\n\n' % (title, len(title) * char) def create_module_file(root, package, module, opts): """Build the text of the file and write the file.""" name = create_file_name(module, opts) if not opts.force and os.path.isfile(name): print 'File %s already exists.' % name elif check_for_code('%s/%s.py' % (root, module)): # don't build the file if there's no code in it print 'Creating file %s for module.' % name text = write_heading(module) text += write_sub(module) text += write_directive(package, module) # write the file if not opts.dryrun: fd = open(name, 'w') fd.write(text) fd.close() def create_package_file(root, subroot, py_files, opts, subs=None): """Build the text of the file and write the file.""" package = root.rpartition('/')[2].lower() name = create_file_name(subroot, opts) if not opts.force and os.path.isfile(name): print 'File %s already exists.' % name else: print 'Creating file %s for package.' % name text = write_heading(package, 'Package') if subs == None: subs = [] else: # build a list of directories that are package (they contain an __init_.py file) subs = [sub for sub in subs if os.path.isfile('%s/%s/__init__.py' % (root, sub))] # if there's some package directories, add a TOC for theses subpackages if subs: text += title_line('Subpackages', '-') text += '.. toctree::\n\n' for sub in subs: text += ' %s.%s\n' % (subroot, sub) text += '\n' # add each package's module for py_file in py_files: if not check_for_code('%s/%s' % (root, py_file)): # don't build the file if there's no code in it continue py_file = py_file[:-3] py_path = '%s.%s' % (subroot, py_file) kind = "Module" if py_file == '__init__': kind = "Package" text += write_sub(kind == 'Package' and package or py_file, kind) text += write_directive(kind == "Package" and subroot or py_path) text += '\n' # write the file if not opts.dryrun: fd = open(name, 'w') fd.write(text) fd.close() def check_for_code(module): """ Check if there's at least one class or one function in the module. """ fd = open(module, 'r') for line in fd: if line.startswith('def ') or line.startswith('class '): fd.close() return True fd.close() return False def recurse_tree(path, excludes, opts): """ Look for every file in the directory tree and create the corresponding ReST files. """ package_name = os.path.split(path)[-1] print 'package name', package_name toc = [] excludes = format_excludes(path, excludes) tree = os.walk(path, False) for root, subs, files in tree: # keep only the Python script files py_files = check_py_file(files) # remove hidden ('.') and private ('_') directories subs = [sub for sub in subs if sub[0] not in ['.', '_']] # check if there's valid files to process if "/." in root or "/_" in root \ or not py_files \ or check_excludes(root, excludes): continue subroot = root[len(path):].lstrip('/').replace('/', '.') if root == path: # we are at the root level so we create only modules for py_file in py_files: module = py_file[:-3] create_module_file(root, package_name, module, opts) if not check_for_code(os.path.join(path, module+'.py')): # don't build the file if there's no code in it pass else: toc.append(module) elif not subs and "__init__.py" in py_files: # we are in a package without sub package create_package_file(root, subroot, py_files, opts=opts) # FIXME: HERE THE __init__.py should go into the toc only if it contains # code! if not check_for_code(subroot): # don't build the file if there's no code in it continue toc.append(subroot) print 'here' elif "__init__.py" in py_files: # we are in package with subpackage(s) create_package_file(root, subroot, py_files, opts, subs) toc.append(subroot) print 'hello' # create the module's index if not opts.notoc: modules_toc(toc, opts) def modules_toc(modules, opts, name='modules'): """ Create the module's index. """ fname = create_file_name(name, opts) if not opts.force and os.path.exists(fname): print "File %s already exists." % name return print "Creating module's index modules.txt." text = write_heading(opts.header, 'Modules') text += title_line('Modules:', '-') text += '.. toctree::\n' text += ' :maxdepth: %s\n\n' % opts.maxdepth modules.sort() prev_module = '' for module in modules: # look if the module is a subpackage and, if yes, ignore it if module.startswith(prev_module + '.'): continue prev_module = module text += ' %s\n' % module # write the file if not opts.dryrun: fd = open(fname, 'w') fd.write(text) fd.close() def format_excludes(path, excludes): """ Format the excluded directory list. (verify that the path is not from the root of the volume or the root of the package) """ f_excludes = [] for exclude in excludes: if exclude[0] != '/' and exclude[:len(path)] != path: exclude = '%s/%s' % (path, exclude) # remove trailing slash f_excludes.append(exclude.rstrip('/')) return f_excludes def check_excludes(root, excludes): """ Check if the directory is in the exclude list. """ for exclude in excludes: if root[:len(exclude)] == exclude: return True return False def check_py_file(files): """ Return a list with only the python scripts (remove all other files). """ py_files = [fich for fich in files if fich[-3:] == '.py'] return py_files if __name__ == '__main__': parser = optparse.OptionParser(usage="""usage: %prog [options] <package path> [exclude paths, ...] Note: By default this script will not overwrite already created files.""") parser.add_option("-n", "--doc-header", action="store", dest="header", help="Documentation Header (default=Project)", default="Project") parser.add_option("-d", "--dest-dir", action="store", dest="destdir", help="Output destination directory", default="") parser.add_option("-s", "--suffix", action="store", dest="suffix", help="module suffix (default=txt)", default="txt") parser.add_option("-m", "--maxdepth", action="store", dest="maxdepth", help="Maximum depth of submodules to show in the TOC (default=4)", type="int", default=4) parser.add_option("-r", "--dry-run", action="store_true", dest="dryrun", help="Run the script without creating the files") parser.add_option("-f", "--force", action="store_true", dest="force", help="Overwrite all the files") parser.add_option("-t", "--no-toc", action="store_true", dest="notoc", help="Don't create the table of content file") (opts, args) = parser.parse_args() if len(args) < 1: parser.error("package path is required.") else: if os.path.isdir(args[0]): # if there's some exclude arguments, build the list of excludes excludes = args[1:] recurse_tree(args[0], excludes, opts) else: print '%s is not a valid directory.' % args
11ghenrylv-mongotest
doc/sphinxext/local/generate_modules_modif.py
Python
lgpl
10,249
#!/usr/bin/env python # -*- coding: utf-8 -*- # Sropulpof # Copyright (C) 2008 Société des arts technologiques (SAT) # http://www.sat.qc.ca # All rights reserved. # # This file 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. # # Sropulpof 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 Sropulpof. If not, see <http:#www.gnu.org/licenses/>. """ This script parse a directory tree looking for python modules and packages and create ReST files appropriately to create code documentation with Sphinx. It also create a modules index. """ import os import optparse # automodule options options = ['members', 'undoc-members', # 'inherited-members', # disable because there's a bug in sphinx 'show-inheritance'] def create_file_name(base, opts): """Create file name from base name, path and suffix""" return os.path.join(opts.destdir, "%s.%s" % (base, opts.suffix)) def write_directive(module): """Create the automodule directive and add the options""" directive = '.. automodule:: %s\n' % module for option in options: directive += ' :%s:\n' % option return directive def write_heading(module, kind='Module'): """Create the page heading.""" module = module.title() heading = title_line(module + ' Documentation', '=') heading += 'This page contains the %s %s documentation.\n\n' % (module, kind) return heading def write_sub(module, kind='Module'): """Create the module subtitle""" sub = title_line('The :mod:`%s` %s' % (module, kind), '-') return sub def title_line(title, char): """ Underline the title with the character pass, with the right length.""" return '%s\n%s\n\n' % (title, len(title) * char) def create_module_file(root, module, opts): """Build the text of the file and write the file.""" name = create_file_name(module, opts) if not opts.force and os.path.isfile(name): print 'File %s already exists.' % name elif check_for_code('%s/%s.py' % (root, module)): # don't build the file if there's no code in it print 'Creating file %s for module.' % name text = write_heading(module) text += write_sub(module) text += write_directive(module) # write the file if not opts.dryrun: fd = open(name, 'w') fd.write(text) fd.close() def create_package_file(root, subroot, py_files, opts, subs=None): """Build the text of the file and write the file.""" package = root.rpartition('/')[2].lower() name = create_file_name(subroot, opts) if not opts.force and os.path.isfile(name): print 'File %s already exists.' % name else: print 'Creating file %s for package.' % name text = write_heading(package, 'Package') if subs == None: subs = [] else: # build a list of directories that are package (they contain an __init_.py file) subs = [sub for sub in subs if os.path.isfile('%s/%s/__init__.py' % (root, sub))] # if there's some package directories, add a TOC for theses subpackages if subs: text += title_line('Subpackages', '-') text += '.. toctree::\n\n' for sub in subs: text += ' %s.%s\n' % (subroot, sub) text += '\n' # add each package's module for py_file in py_files: if not check_for_code('%s/%s' % (root, py_file)): # don't build the file if there's no code in it continue py_file = py_file[:-3] py_path = '%s.%s' % (subroot, py_file) kind = "Module" if py_file == '__init__': kind = "Package" text += write_sub(kind == 'Package' and package or py_file, kind) text += write_directive(kind == "Package" and subroot or py_path) text += '\n' # write the file if not opts.dryrun: fd = open(name, 'w') fd.write(text) fd.close() def check_for_code(module): """ Check if there's at least one class or one function in the module. """ fd = open(module, 'r') for line in fd: if line.startswith('def ') or line.startswith('class '): fd.close() return True fd.close() return False def recurse_tree(path, excludes, opts): """ Look for every file in the directory tree and create the corresponding ReST files. """ toc = [] excludes = format_excludes(path, excludes) tree = os.walk(path, False) for root, subs, files in tree: # keep only the Python script files py_files = check_py_file(files) # remove hidden ('.') and private ('_') directories subs = [sub for sub in subs if sub[0] not in ['.', '_']] # check if there's valid files to process if "/." in root or "/_" in root \ or not py_files \ or check_excludes(root, excludes): continue subroot = root[len(path):].lstrip('/').replace('/', '.') if root == path: # we are at the root level so we create only modules for py_file in py_files: module = py_file[:-3] create_module_file(root, module, opts) toc.append(module) elif not subs and "__init__.py" in py_files: # we are in a package without sub package create_package_file(root, subroot, py_files, opts=opts) toc.append(subroot) elif "__init__.py" in py_files: # we are in package with subpackage(s) create_package_file(root, subroot, py_files, opts, subs) toc.append(subroot) # create the module's index if not opts.notoc: modules_toc(toc, opts) def modules_toc(modules, opts, name='modules'): """ Create the module's index. """ fname = create_file_name(name, opts) if not opts.force and os.path.exists(fname): print "File %s already exists." % name return print "Creating module's index modules.txt." text = write_heading(opts.header, 'Modules') text += title_line('Modules:', '-') text += '.. toctree::\n' text += ' :maxdepth: %s\n\n' % opts.maxdepth modules.sort() prev_module = '' for module in modules: # look if the module is a subpackage and, if yes, ignore it if module.startswith(prev_module + '.'): continue prev_module = module text += ' %s\n' % module # write the file if not opts.dryrun: fd = open(fname, 'w') fd.write(text) fd.close() def format_excludes(path, excludes): """ Format the excluded directory list. (verify that the path is not from the root of the volume or the root of the package) """ f_excludes = [] for exclude in excludes: if exclude[0] != '/' and exclude[:len(path)] != path: exclude = '%s/%s' % (path, exclude) # remove trailing slash f_excludes.append(exclude.rstrip('/')) return f_excludes def check_excludes(root, excludes): """ Check if the directory is in the exclude list. """ for exclude in excludes: if root[:len(exclude)] == exclude: return True return False def check_py_file(files): """ Return a list with only the python scripts (remove all other files). """ py_files = [fich for fich in files if fich[-3:] == '.py'] return py_files if __name__ == '__main__': parser = optparse.OptionParser(usage="""usage: %prog [options] <package path> [exclude paths, ...] Note: By default this script will not overwrite already created files.""") parser.add_option("-n", "--doc-header", action="store", dest="header", help="Documentation Header (default=Project)", default="Project") parser.add_option("-d", "--dest-dir", action="store", dest="destdir", help="Output destination directory", default="") parser.add_option("-s", "--suffix", action="store", dest="suffix", help="module suffix (default=txt)", default="txt") parser.add_option("-m", "--maxdepth", action="store", dest="maxdepth", help="Maximum depth of submodules to show in the TOC (default=4)", type="int", default=4) parser.add_option("-r", "--dry-run", action="store_true", dest="dryrun", help="Run the script without creating the files") parser.add_option("-f", "--force", action="store_true", dest="force", help="Overwrite all the files") parser.add_option("-t", "--no-toc", action="store_true", dest="notoc", help="Don't create the table of content file") (opts, args) = parser.parse_args() if len(args) < 1: parser.error("package path is required.") else: if os.path.isdir(args[0]): # if there's some exclude arguments, build the list of excludes excludes = args[1:] recurse_tree(args[0], excludes, opts) else: print '%s is not a valid directory.' % args
11ghenrylv-mongotest
doc/sphinxext/local/generate_modules.py
Python
lgpl
9,634
import os import subprocess import codecs #--- BZR: changelog information def write_changelog_bzr(repo_path, output_dir, output_file='bzr_revision_log.txt', target_encoding='utf-8'): """Write the bzr changelog to a file which can then be included in the documentation """ bzr_logfile_path = os.path.join(output_dir, output_file) bzr_logfile = codecs.open(bzr_logfile_path, 'w', encoding=target_encoding) try: p_log = subprocess.Popen(('bzr log --short'), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=-1) (stdout, stderr) = p_log.communicate() bzr_logfile.write(stdout) finally: bzr_logfile.close() #UnicodeDecodeError: 'ascii' codec can't decode byte 0x81 in position 2871: ordinal not in range(128) # like bzr version-info --format python > vers_test.py #--- BZR: version info def write_version_info_bzr(repo_path, output_dir, output_file='_version.py'): """Write the version information from BZR repository into a version file. Parameters ---------- repo_path : string Path to the BZR repository root repo_path : string Path to the output directory where the version info is saved detail, e.g. ``(N,) ndarray`` or ``array_like``. output_file : string output file name Returns ------- p_info : subprocess_obj contents of the `func:`suprocess.Popen` returns """ bzr_version_filepath = os.path.join(output_dir, output_file) bzr_version_file = open(bzr_version_filepath, 'w') p_info = subprocess.Popen(('bzr version-info --format python'), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=-1) (stdout, stderr) = p_info.communicate() bzr_version_file.write(stdout) bzr_version_file.close() return p_info #--- auto generate documentation def autogenerate_package_doc(script_path, dest_dir, package_dir, doc_header, suffix='rst', overwrite=False): """Autogenerate package API ReSt documents """ print script_path if overwrite: force = '--force' p_apidoc = subprocess.Popen(('python', script_path, '--dest-dir='+dest_dir, '--suffix='+suffix, '--doc-header='+doc_header, force, package_dir), bufsize=-1) 'sphinxext\local\generate_modules_modif.py --dest-dir=source\contents\lib\auxilary\generated --suffix=rst --force --doc-header=Auxilary ..\..\modules_local\auxilary' return p_apidoc if __name__ == "__main__": repo_path = os.path.join('..', '.') output_dir = os.path.join('.') write_changelog_bzr(repo_path, output_dir, output_file='changelog.txt')
11ghenrylv-mongotest
doc/sphinxext/local/sphinx_tools.py
Python
lgpl
3,416
""" A special directive for generating a matplotlib plot. .. warning:: This is a hacked version of plot_directive.py from Matplotlib. It's very much subject to change! Usage ----- Can be used like this:: .. plot:: examples/example.py .. plot:: import matplotlib.pyplot as plt plt.plot([1,2,3], [4,5,6]) .. plot:: A plotting example: >>> import matplotlib.pyplot as plt >>> plt.plot([1,2,3], [4,5,6]) The content is interpreted as doctest formatted if it has a line starting with ``>>>``. The ``plot`` directive supports the options format : {'python', 'doctest'} Specify the format of the input include-source : bool Whether to display the source code. Default can be changed in conf.py and the ``image`` directive options ``alt``, ``height``, ``width``, ``scale``, ``align``, ``class``. Configuration options --------------------- The plot directive has the following configuration options: plot_output_dir Directory (relative to config file) where to store plot output. Should be inside the static directory. (Default: 'static') plot_pre_code Code that should be executed before each plot. plot_rcparams Dictionary of Matplotlib rc-parameter overrides. Has 'sane' defaults. plot_include_source Default value for the include-source option plot_formats The set of files to generate. Default: ['png', 'pdf', 'hires.png'], ie. everything. TODO ---- * Don't put temp files to _static directory, but do function in the way the pngmath directive works, and plot figures only during output writing. * Refactor Latex output; now it's plain images, but it would be nice to make them appear side-by-side, or in floats. """ import sys, os, glob, shutil, imp, warnings, cStringIO, re, textwrap import warnings warnings.warn("A plot_directive module is also available under " "matplotlib.sphinxext; expect this numpydoc.plot_directive " "module to be deprecated after relevant features have been " "integrated there.", FutureWarning, stacklevel=2) def setup(app): setup.app = app setup.config = app.config setup.confdir = app.confdir static_path = '_static' if hasattr(app.config, 'html_static_path') and app.config.html_static_path: static_path = app.config.html_static_path[0] app.add_config_value('plot_output_dir', static_path, True) app.add_config_value('plot_pre_code', '', True) app.add_config_value('plot_rcparams', sane_rcparameters, True) app.add_config_value('plot_include_source', False, True) app.add_config_value('plot_formats', ['png', 'hires.png', 'pdf'], True) app.add_directive('plot', plot_directive, True, (0, 1, False), **plot_directive_options) sane_rcparameters = { 'font.size': 9, 'axes.titlesize': 9, 'axes.labelsize': 9, 'xtick.labelsize': 9, 'ytick.labelsize': 9, 'legend.fontsize': 9, 'figure.figsize': (4, 3), } #------------------------------------------------------------------------------ # Run code and capture figures #------------------------------------------------------------------------------ import matplotlib import matplotlib.cbook as cbook matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.image as image from matplotlib import _pylab_helpers def contains_doctest(text): r = re.compile(r'^\s*>>>', re.M) m = r.match(text) return bool(m) def unescape_doctest(text): """ Extract code from a piece of text, which contains either Python code or doctests. """ if not contains_doctest(text): return text code = "" for line in text.split("\n"): m = re.match(r'^\s*(>>>|...) (.*)$', line) if m: code += m.group(2) + "\n" elif line.strip(): code += "# " + line.strip() + "\n" else: code += "\n" return code def run_code(code, code_path): # Change the working directory to the directory of the example, so # it can get at its data files, if any. pwd = os.getcwd() old_sys_path = list(sys.path) if code_path is not None: dirname = os.path.abspath(os.path.dirname(code_path)) os.chdir(dirname) sys.path.insert(0, dirname) # Redirect stdout stdout = sys.stdout sys.stdout = cStringIO.StringIO() try: code = unescape_doctest(code) ns = {} exec setup.config.plot_pre_code in ns exec code in ns finally: os.chdir(pwd) sys.path[:] = old_sys_path sys.stdout = stdout return ns #------------------------------------------------------------------------------ # Generating figures #------------------------------------------------------------------------------ def out_of_date(original, derived): """ Returns True if derivative is out-of-date wrt original, both of which are full file paths. """ return (not os.path.exists(derived) or os.stat(derived).st_mtime < os.stat(original).st_mtime) def makefig(code, code_path, output_dir, output_base, config): """ run a pyplot script and save the low and high res PNGs and a PDF in _static """ included_formats = config.plot_formats if type(included_formats) is str: included_formats = eval(included_formats) formats = [x for x in [('png', 80), ('hires.png', 200), ('pdf', 50)] if x[0] in config.plot_formats] all_exists = True # Look for single-figure output files first for format, dpi in formats: output_path = os.path.join(output_dir, '%s.%s' % (output_base, format)) if out_of_date(code_path, output_path): all_exists = False break if all_exists: return [output_base] # Then look for multi-figure output files image_names = [] for i in xrange(1000): image_names.append('%s_%02d' % (output_base, i)) for format, dpi in formats: output_path = os.path.join(output_dir, '%s.%s' % (image_names[-1], format)) if out_of_date(code_path, output_path): all_exists = False break if not all_exists: # assume that if we have one, we have them all all_exists = (i > 0) break if all_exists: return image_names # We didn't find the files, so build them print "-- Plotting figures %s" % output_base # Clear between runs plt.close('all') # Reset figure parameters matplotlib.rcdefaults() matplotlib.rcParams.update(config.plot_rcparams) # Run code run_code(code, code_path) # Collect images image_names = [] fig_managers = _pylab_helpers.Gcf.get_all_fig_managers() for i, figman in enumerate(fig_managers): if len(fig_managers) == 1: name = output_base else: name = "%s_%02d" % (output_base, i) image_names.append(name) for format, dpi in formats: path = os.path.join(output_dir, '%s.%s' % (name, format)) figman.canvas.figure.savefig(path, dpi=dpi) return image_names #------------------------------------------------------------------------------ # Generating output #------------------------------------------------------------------------------ from docutils import nodes, utils import jinja TEMPLATE = """ {{source_code}} .. htmlonly:: {% if source_code %} (`Source code <{{source_link}}>`__) {% endif %} .. admonition:: Output :class: plot-output {% for name in image_names %} .. figure:: {{link_dir}}/{{name}}.png {%- for option in options %} {{option}} {% endfor %} ( {%- if not source_code %}`Source code <{{source_link}}>`__, {% endif -%} `PNG <{{link_dir}}/{{name}}.hires.png>`__, `PDF <{{link_dir}}/{{name}}.pdf>`__) {% endfor %} .. latexonly:: {% for name in image_names %} .. image:: {{link_dir}}/{{name}}.pdf {% endfor %} """ def run(arguments, content, options, state_machine, state, lineno): if arguments and content: raise RuntimeError("plot:: directive can't have both args and content") document = state_machine.document config = document.settings.env.config options.setdefault('include-source', config.plot_include_source) if options['include-source'] is None: options['include-source'] = config.plot_include_source # determine input rst_file = document.attributes['source'] rst_dir = os.path.dirname(rst_file) if arguments: file_name = os.path.join(rst_dir, directives.uri(arguments[0])) code = open(file_name, 'r').read() output_base = os.path.basename(file_name) else: file_name = rst_file code = textwrap.dedent("\n".join(map(str, content))) counter = document.attributes.get('_plot_counter', 0) + 1 document.attributes['_plot_counter'] = counter output_base = '%d-%s' % (counter, os.path.basename(file_name)) rel_name = relpath(file_name, setup.confdir) base, ext = os.path.splitext(output_base) if ext in ('.py', '.rst', '.txt'): output_base = base # is it in doctest format? is_doctest = contains_doctest(code) if options.has_key('format'): if options['format'] == 'python': is_doctest = False else: is_doctest = True # determine output file_rel_dir = os.path.dirname(rel_name) while file_rel_dir.startswith(os.path.sep): file_rel_dir = file_rel_dir[1:] output_dir = os.path.join(setup.confdir, setup.config.plot_output_dir, file_rel_dir) if not os.path.exists(output_dir): cbook.mkdirs(output_dir) # copy script target_name = os.path.join(output_dir, output_base) f = open(target_name, 'w') f.write(unescape_doctest(code)) f.close() source_link = relpath(target_name, rst_dir) # determine relative reference link_dir = relpath(output_dir, rst_dir) # make figures try: image_names = makefig(code, file_name, output_dir, output_base, config) except RuntimeError, err: reporter = state.memo.reporter sm = reporter.system_message(3, "Exception occurred rendering plot", line=lineno) return [sm] # generate output if options['include-source']: if is_doctest: lines = [''] else: lines = ['.. code-block:: python', ''] lines += [' %s' % row.rstrip() for row in code.split('\n')] source_code = "\n".join(lines) else: source_code = "" opts = [':%s: %s' % (key, val) for key, val in options.items() if key in ('alt', 'height', 'width', 'scale', 'align', 'class')] result = jinja.from_string(TEMPLATE).render( link_dir=link_dir.replace(os.path.sep, '/'), source_link=source_link, options=opts, image_names=image_names, source_code=source_code) lines = result.split("\n") if len(lines): state_machine.insert_input( lines, state_machine.input_lines.source(0)) return [] if hasattr(os.path, 'relpath'): relpath = os.path.relpath else: def relpath(target, base=os.curdir): """ Return a relative path to the target from either the current dir or an optional base dir. Base can be a directory specified either as absolute or relative to current dir. """ if not os.path.exists(target): raise OSError, 'Target does not exist: '+target if not os.path.isdir(base): raise OSError, 'Base is not a directory or does not exist: '+base base_list = (os.path.abspath(base)).split(os.sep) target_list = (os.path.abspath(target)).split(os.sep) # On the windows platform the target may be on a completely # different drive from the base. if os.name in ['nt','dos','os2'] and base_list[0] <> target_list[0]: raise OSError, 'Target is on a different drive to base. Target: '+target_list[0].upper()+', base: '+base_list[0].upper() # Starting from the filepath root, work out how much of the # filepath is shared by base and target. for i in range(min(len(base_list), len(target_list))): if base_list[i] <> target_list[i]: break else: # If we broke out of the loop, i is pointing to the first # differing path elements. If we didn't break out of the # loop, i is pointing to identical path elements. # Increment i so that in all cases it points to the first # differing path elements. i+=1 rel_list = [os.pardir] * (len(base_list)-i) + target_list[i:] return os.path.join(*rel_list) #------------------------------------------------------------------------------ # plot:: directive registration etc. #------------------------------------------------------------------------------ from docutils.parsers.rst import directives try: # docutils 0.4 from docutils.parsers.rst.directives.images import align except ImportError: # docutils 0.5 from docutils.parsers.rst.directives.images import Image align = Image.align def plot_directive(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): return run(arguments, content, options, state_machine, state, lineno) plot_directive.__doc__ = __doc__ def _option_boolean(arg): if not arg or not arg.strip(): return None elif arg.strip().lower() in ('no', '0', 'false'): return False elif arg.strip().lower() in ('yes', '1', 'true'): return True else: raise ValueError('"%s" unknown boolean' % arg) def _option_format(arg): return directives.choice(arg, ('python', 'lisp')) plot_directive_options = {'alt': directives.unchanged, 'height': directives.length_or_unitless, 'width': directives.length_or_percentage_or_unitless, 'scale': directives.nonnegative_int, 'align': align, 'class': directives.class_option, 'include-source': _option_boolean, 'format': _option_format, }
11ghenrylv-mongotest
doc/sphinxext/numpydoc/plot_directive.py
Python
lgpl
14,687
"""Extract reference documentation from the NumPy source tree. """ import inspect import textwrap import re import pydoc from StringIO import StringIO from warnings import warn 4 class Reader(object): """A line-based string reader. """ def __init__(self, data): """ Parameters ---------- data : str String with lines separated by '\n'. """ if isinstance(data,list): self._str = data else: self._str = data.split('\n') # store string as list of lines self.reset() def __getitem__(self, n): return self._str[n] def reset(self): self._l = 0 # current line nr def read(self): if not self.eof(): out = self[self._l] self._l += 1 return out else: return '' def seek_next_non_empty_line(self): for l in self[self._l:]: if l.strip(): break else: self._l += 1 def eof(self): return self._l >= len(self._str) def read_to_condition(self, condition_func): start = self._l for line in self[start:]: if condition_func(line): return self[start:self._l] self._l += 1 if self.eof(): return self[start:self._l+1] return [] def read_to_next_empty_line(self): self.seek_next_non_empty_line() def is_empty(line): return not line.strip() return self.read_to_condition(is_empty) def read_to_next_unindented_line(self): def is_unindented(line): return (line.strip() and (len(line.lstrip()) == len(line))) return self.read_to_condition(is_unindented) def peek(self,n=0): if self._l + n < len(self._str): return self[self._l + n] else: return '' def is_empty(self): return not ''.join(self._str).strip() class NumpyDocString(object): def __init__(self,docstring): docstring = textwrap.dedent(docstring).split('\n') self._doc = Reader(docstring) self._parsed_data = { 'Signature': '', 'Summary': [''], 'Extended Summary': [], 'Parameters': [], 'Returns': [], 'Raises': [], 'Warns': [], 'Other Parameters': [], 'Attributes': [], 'Methods': [], 'See Also': [], 'Notes': [], 'Warnings': [], 'References': '', 'Examples': '', 'index': {} } self._parse() def __getitem__(self,key): return self._parsed_data[key] def __setitem__(self,key,val): if not self._parsed_data.has_key(key): warn("Unknown section %s" % key) else: self._parsed_data[key] = val def _is_at_section(self): self._doc.seek_next_non_empty_line() if self._doc.eof(): return False l1 = self._doc.peek().strip() # e.g. Parameters if l1.startswith('.. index::'): return True l2 = self._doc.peek(1).strip() # ---------- or ========== return l2.startswith('-'*len(l1)) or l2.startswith('='*len(l1)) def _strip(self,doc): i = 0 j = 0 for i,line in enumerate(doc): if line.strip(): break for j,line in enumerate(doc[::-1]): if line.strip(): break return doc[i:len(doc)-j] def _read_to_next_section(self): section = self._doc.read_to_next_empty_line() while not self._is_at_section() and not self._doc.eof(): if not self._doc.peek(-1).strip(): # previous line was empty section += [''] section += self._doc.read_to_next_empty_line() return section def _read_sections(self): while not self._doc.eof(): data = self._read_to_next_section() name = data[0].strip() if name.startswith('..'): # index section yield name, data[1:] elif len(data) < 2: yield StopIteration else: yield name, self._strip(data[2:]) def _parse_param_list(self,content): r = Reader(content) params = [] while not r.eof(): header = r.read().strip() if ' : ' in header: arg_name, arg_type = header.split(' : ')[:2] else: arg_name, arg_type = header, '' desc = r.read_to_next_unindented_line() desc = dedent_lines(desc) params.append((arg_name,arg_type,desc)) return params _name_rgx = re.compile(r"^\s*(:(?P<role>\w+):`(?P<name>[a-zA-Z0-9_.-]+)`|" r" (?P<name2>[a-zA-Z0-9_.-]+))\s*", re.X) def _parse_see_also(self, content): """ func_name : Descriptive text continued text another_func_name : Descriptive text func_name1, func_name2, :meth:`func_name`, func_name3 """ items = [] def parse_item_name(text): """Match ':role:`name`' or 'name'""" m = self._name_rgx.match(text) if m: g = m.groups() if g[1] is None: return g[3], None else: return g[2], g[1] raise ValueError("%s is not a item name" % text) def push_item(name, rest): if not name: return name, role = parse_item_name(name) items.append((name, list(rest), role)) del rest[:] current_func = None rest = [] for line in content: if not line.strip(): continue m = self._name_rgx.match(line) if m and line[m.end():].strip().startswith(':'): push_item(current_func, rest) current_func, line = line[:m.end()], line[m.end():] rest = [line.split(':', 1)[1].strip()] if not rest[0]: rest = [] elif not line.startswith(' '): push_item(current_func, rest) current_func = None if ',' in line: for func in line.split(','): push_item(func, []) elif line.strip(): current_func = line elif current_func is not None: rest.append(line.strip()) push_item(current_func, rest) return items def _parse_index(self, section, content): """ .. index: default :refguide: something, else, and more """ def strip_each_in(lst): return [s.strip() for s in lst] out = {} section = section.split('::') if len(section) > 1: out['default'] = strip_each_in(section[1].split(','))[0] for line in content: line = line.split(':') if len(line) > 2: out[line[1]] = strip_each_in(line[2].split(',')) return out def _parse_summary(self): """Grab signature (if given) and summary""" if self._is_at_section(): return summary = self._doc.read_to_next_empty_line() summary_str = " ".join([s.strip() for s in summary]).strip() if re.compile('^([\w., ]+=)?\s*[\w\.]+\(.*\)$').match(summary_str): self['Signature'] = summary_str if not self._is_at_section(): self['Summary'] = self._doc.read_to_next_empty_line() else: self['Summary'] = summary if not self._is_at_section(): self['Extended Summary'] = self._read_to_next_section() def _parse(self): self._doc.reset() self._parse_summary() for (section,content) in self._read_sections(): if not section.startswith('..'): section = ' '.join([s.capitalize() for s in section.split(' ')]) if section in ('Parameters', 'Attributes', 'Methods', 'Returns', 'Raises', 'Warns'): self[section] = self._parse_param_list(content) elif section.startswith('.. index::'): self['index'] = self._parse_index(section, content) elif section == 'See Also': self['See Also'] = self._parse_see_also(content) else: self[section] = content # string conversion routines def _str_header(self, name, symbol='-'): return [name, len(name)*symbol] def _str_indent(self, doc, indent=4): out = [] for line in doc: out += [' '*indent + line] return out def _str_signature(self): if self['Signature']: return [self['Signature'].replace('*','\*')] + [''] else: return [''] def _str_summary(self): if self['Summary']: return self['Summary'] + [''] else: return [] def _str_extended_summary(self): if self['Extended Summary']: return self['Extended Summary'] + [''] else: return [] def _str_param_list(self, name): out = [] if self[name]: out += self._str_header(name) for param,param_type,desc in self[name]: out += ['%s : %s' % (param, param_type)] out += self._str_indent(desc) out += [''] return out def _str_section(self, name): out = [] if self[name]: out += self._str_header(name) out += self[name] out += [''] return out def _str_see_also(self, func_role): if not self['See Also']: return [] out = [] out += self._str_header("See Also") last_had_desc = True for func, desc, role in self['See Also']: if role: link = ':%s:`%s`' % (role, func) elif func_role: link = ':%s:`%s`' % (func_role, func) else: link = "`%s`_" % func if desc or last_had_desc: out += [''] out += [link] else: out[-1] += ", %s" % link if desc: out += self._str_indent([' '.join(desc)]) last_had_desc = True else: last_had_desc = False out += [''] return out def _str_index(self): idx = self['index'] out = [] out += ['.. index:: %s' % idx.get('default','')] for section, references in idx.iteritems(): if section == 'default': continue out += [' :%s: %s' % (section, ', '.join(references))] return out def __str__(self, func_role=''): out = [] out += self._str_signature() out += self._str_summary() out += self._str_extended_summary() for param_list in ('Parameters','Returns','Raises'): out += self._str_param_list(param_list) out += self._str_section('Warnings') out += self._str_see_also(func_role) for s in ('Notes','References','Examples'): out += self._str_section(s) out += self._str_index() return '\n'.join(out) def indent(str,indent=4): indent_str = ' '*indent if str is None: return indent_str lines = str.split('\n') return '\n'.join(indent_str + l for l in lines) def dedent_lines(lines): """Deindent a list of lines maximally""" return textwrap.dedent("\n".join(lines)).split("\n") def header(text, style='-'): return text + '\n' + style*len(text) + '\n' class FunctionDoc(NumpyDocString): def __init__(self, func, role='func', doc=None): self._f = func self._role = role # e.g. "func" or "meth" if doc is None: doc = inspect.getdoc(func) or '' try: NumpyDocString.__init__(self, doc) except ValueError, e: print '*'*78 print "ERROR: '%s' while parsing `%s`" % (e, self._f) print '*'*78 #print "Docstring follows:" #print doclines #print '='*78 if not self['Signature']: func, func_name = self.get_func() try: # try to read signature argspec = inspect.getargspec(func) argspec = inspect.formatargspec(*argspec) argspec = argspec.replace('*','\*') signature = '%s%s' % (func_name, argspec) except TypeError, e: signature = '%s()' % func_name self['Signature'] = signature def get_func(self): func_name = getattr(self._f, '__name__', self.__class__.__name__) if inspect.isclass(self._f): func = getattr(self._f, '__call__', self._f.__init__) else: func = self._f return func, func_name def __str__(self): out = '' func, func_name = self.get_func() signature = self['Signature'].replace('*', '\*') roles = {'func': 'function', 'meth': 'method'} if self._role: if not roles.has_key(self._role): print "Warning: invalid role %s" % self._role out += '.. %s:: %s\n \n\n' % (roles.get(self._role,''), func_name) out += super(FunctionDoc, self).__str__(func_role=self._role) return out class ClassDoc(NumpyDocString): def __init__(self,cls,modulename='',func_doc=FunctionDoc,doc=None): if not inspect.isclass(cls): raise ValueError("Initialise using a class. Got %r" % cls) self._cls = cls if modulename and not modulename.endswith('.'): modulename += '.' self._mod = modulename self._name = cls.__name__ self._func_doc = func_doc if doc is None: doc = pydoc.getdoc(cls) NumpyDocString.__init__(self, doc) @property def methods(self): return [name for name,func in inspect.getmembers(self._cls) if not name.startswith('_') and callable(func)] def __str__(self): out = '' out += super(ClassDoc, self).__str__() out += "\n\n" #for m in self.methods: # print "Parsing `%s`" % m # out += str(self._func_doc(getattr(self._cls,m), 'meth')) + '\n\n' # out += '.. index::\n single: %s; %s\n\n' % (self._name, m) return out
11ghenrylv-mongotest
doc/sphinxext/numpydoc/docscrape.py
Python
lgpl
14,838
# # A pair of directives for inserting content that will only appear in # either html or latex. # from docutils.nodes import Body, Element from docutils.writers.html4css1 import HTMLTranslator try: from sphinx.latexwriter import LaTeXTranslator except ImportError: from sphinx.writers.latex import LaTeXTranslator import warnings warnings.warn("The numpydoc.only_directives module is deprecated;" "please use the only:: directive available in Sphinx >= 0.6", DeprecationWarning, stacklevel=2) from docutils.parsers.rst import directives class html_only(Body, Element): pass class latex_only(Body, Element): pass def run(content, node_class, state, content_offset): text = '\n'.join(content) node = node_class(text) state.nested_parse(content, content_offset, node) return [node] try: from docutils.parsers.rst import Directive except ImportError: from docutils.parsers.rst.directives import _directives def html_only_directive(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): return run(content, html_only, state, content_offset) def latex_only_directive(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): return run(content, latex_only, state, content_offset) for func in (html_only_directive, latex_only_directive): func.content = 1 func.options = {} func.arguments = None _directives['htmlonly'] = html_only_directive _directives['latexonly'] = latex_only_directive else: class OnlyDirective(Directive): has_content = True required_arguments = 0 optional_arguments = 0 final_argument_whitespace = True option_spec = {} def run(self): self.assert_has_content() return run(self.content, self.node_class, self.state, self.content_offset) class HtmlOnlyDirective(OnlyDirective): node_class = html_only class LatexOnlyDirective(OnlyDirective): node_class = latex_only directives.register_directive('htmlonly', HtmlOnlyDirective) directives.register_directive('latexonly', LatexOnlyDirective) def setup(app): app.add_node(html_only) app.add_node(latex_only) # Add visit/depart methods to HTML-Translator: def visit_perform(self, node): pass def depart_perform(self, node): pass def visit_ignore(self, node): node.children = [] def depart_ignore(self, node): node.children = [] HTMLTranslator.visit_html_only = visit_perform HTMLTranslator.depart_html_only = depart_perform HTMLTranslator.visit_latex_only = visit_ignore HTMLTranslator.depart_latex_only = depart_ignore LaTeXTranslator.visit_html_only = visit_ignore LaTeXTranslator.depart_html_only = depart_ignore LaTeXTranslator.visit_latex_only = visit_perform LaTeXTranslator.depart_latex_only = depart_perform
11ghenrylv-mongotest
doc/sphinxext/numpydoc/only_directives.py
Python
lgpl
3,093
from cStringIO import StringIO import compiler import inspect import textwrap import tokenize from compiler_unparse import unparse class Comment(object): """ A comment block. """ is_comment = True def __init__(self, start_lineno, end_lineno, text): # int : The first line number in the block. 1-indexed. self.start_lineno = start_lineno # int : The last line number. Inclusive! self.end_lineno = end_lineno # str : The text block including '#' character but not any leading spaces. self.text = text def add(self, string, start, end, line): """ Add a new comment line. """ self.start_lineno = min(self.start_lineno, start[0]) self.end_lineno = max(self.end_lineno, end[0]) self.text += string def __repr__(self): return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno, self.end_lineno, self.text) class NonComment(object): """ A non-comment block of code. """ is_comment = False def __init__(self, start_lineno, end_lineno): self.start_lineno = start_lineno self.end_lineno = end_lineno def add(self, string, start, end, line): """ Add lines to the block. """ if string.strip(): # Only add if not entirely whitespace. self.start_lineno = min(self.start_lineno, start[0]) self.end_lineno = max(self.end_lineno, end[0]) def __repr__(self): return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno, self.end_lineno) class CommentBlocker(object): """ Pull out contiguous comment blocks. """ def __init__(self): # Start with a dummy. self.current_block = NonComment(0, 0) # All of the blocks seen so far. self.blocks = [] # The index mapping lines of code to their associated comment blocks. self.index = {} def process_file(self, file): """ Process a file object. """ for token in tokenize.generate_tokens(file.next): self.process_token(*token) self.make_index() def process_token(self, kind, string, start, end, line): """ Process a single token. """ if self.current_block.is_comment: if kind == tokenize.COMMENT: self.current_block.add(string, start, end, line) else: self.new_noncomment(start[0], end[0]) else: if kind == tokenize.COMMENT: self.new_comment(string, start, end, line) else: self.current_block.add(string, start, end, line) def new_noncomment(self, start_lineno, end_lineno): """ We are transitioning from a noncomment to a comment. """ block = NonComment(start_lineno, end_lineno) self.blocks.append(block) self.current_block = block def new_comment(self, string, start, end, line): """ Possibly add a new comment. Only adds a new comment if this comment is the only thing on the line. Otherwise, it extends the noncomment block. """ prefix = line[:start[1]] if prefix.strip(): # Oops! Trailing comment, not a comment block. self.current_block.add(string, start, end, line) else: # A comment block. block = Comment(start[0], end[0], string) self.blocks.append(block) self.current_block = block def make_index(self): """ Make the index mapping lines of actual code to their associated prefix comments. """ for prev, block in zip(self.blocks[:-1], self.blocks[1:]): if not block.is_comment: self.index[block.start_lineno] = prev def search_for_comment(self, lineno, default=None): """ Find the comment block just before the given line number. Returns None (or the specified default) if there is no such block. """ if not self.index: self.make_index() block = self.index.get(lineno, None) text = getattr(block, 'text', default) return text def strip_comment_marker(text): """ Strip # markers at the front of a block of comment text. """ lines = [] for line in text.splitlines(): lines.append(line.lstrip('#')) text = textwrap.dedent('\n'.join(lines)) return text def get_class_traits(klass): """ Yield all of the documentation for trait definitions on a class object. """ # FIXME: gracefully handle errors here or in the caller? source = inspect.getsource(klass) cb = CommentBlocker() cb.process_file(StringIO(source)) mod_ast = compiler.parse(source) class_ast = mod_ast.node.nodes[0] for node in class_ast.code.nodes: # FIXME: handle other kinds of assignments? if isinstance(node, compiler.ast.Assign): name = node.nodes[0].name rhs = unparse(node.expr).strip() doc = strip_comment_marker(cb.search_for_comment(node.lineno, default='')) yield name, rhs, doc
11ghenrylv-mongotest
doc/sphinxext/numpydoc/comment_eater.py
Python
lgpl
5,181
""" =========== autosummary =========== Sphinx extension that adds an autosummary:: directive, which can be used to generate function/method/attribute/etc. summary lists, similar to those output eg. by Epydoc and other API doc generation tools. An :autolink: role is also provided. autosummary directive --------------------- The autosummary directive has the form:: .. autosummary:: :nosignatures: :toctree: generated/ module.function_1 module.function_2 ... and it generates an output table (containing signatures, optionally) ======================== ============================================= module.function_1(args) Summary line from the docstring of function_1 module.function_2(args) Summary line from the docstring ... ======================== ============================================= If the :toctree: option is specified, files matching the function names are inserted to the toctree with the given prefix: generated/module.function_1 generated/module.function_2 ... Note: The file names contain the module:: or currentmodule:: prefixes. .. seealso:: autosummary_generate.py autolink role ------------- The autolink role functions as ``:obj:`` when the name referred can be resolved to a Python object, and otherwise it becomes simple emphasis. This can be used as the default role to make links 'smart'. """ import sys, os, posixpath, re from docutils.parsers.rst import directives from docutils.statemachine import ViewList from docutils import nodes import sphinx.addnodes, sphinx.roles from sphinx.util import patfilter from docscrape_sphinx import get_doc_object import warnings warnings.warn( "The numpydoc.autosummary extension can also be found as " "sphinx.ext.autosummary in Sphinx >= 0.6, and the version in " "Sphinx >= 0.7 is superior to the one in numpydoc. This numpydoc " "version of autosummary is no longer maintained.", DeprecationWarning, stacklevel=2) def setup(app): app.add_directive('autosummary', autosummary_directive, True, (0, 0, False), toctree=directives.unchanged, nosignatures=directives.flag) app.add_role('autolink', autolink_role) app.add_node(autosummary_toc, html=(autosummary_toc_visit_html, autosummary_toc_depart_noop), latex=(autosummary_toc_visit_latex, autosummary_toc_depart_noop)) app.connect('doctree-read', process_autosummary_toc) #------------------------------------------------------------------------------ # autosummary_toc node #------------------------------------------------------------------------------ class autosummary_toc(nodes.comment): pass def process_autosummary_toc(app, doctree): """ Insert items described in autosummary:: to the TOC tree, but do not generate the toctree:: list. """ env = app.builder.env crawled = {} def crawl_toc(node, depth=1): crawled[node] = True for j, subnode in enumerate(node): try: if (isinstance(subnode, autosummary_toc) and isinstance(subnode[0], sphinx.addnodes.toctree)): env.note_toctree(env.docname, subnode[0]) continue except IndexError: continue if not isinstance(subnode, nodes.section): continue if subnode not in crawled: crawl_toc(subnode, depth+1) crawl_toc(doctree) def autosummary_toc_visit_html(self, node): """Hide autosummary toctree list in HTML output""" raise nodes.SkipNode def autosummary_toc_visit_latex(self, node): """Show autosummary toctree (= put the referenced pages here) in Latex""" pass def autosummary_toc_depart_noop(self, node): pass #------------------------------------------------------------------------------ # .. autosummary:: #------------------------------------------------------------------------------ def autosummary_directive(dirname, arguments, options, content, lineno, content_offset, block_text, state, state_machine): """ Pretty table containing short signatures and summaries of functions etc. autosummary also generates a (hidden) toctree:: node. """ names = [] names += [x.strip().split()[0] for x in content if x.strip() and re.search(r'^[a-zA-Z_]', x.strip()[0])] table, warnings, real_names = get_autosummary(names, state, 'nosignatures' in options) node = table env = state.document.settings.env suffix = env.config.source_suffix all_docnames = env.found_docs.copy() dirname = posixpath.dirname(env.docname) if 'toctree' in options: tree_prefix = options['toctree'].strip() docnames = [] for name in names: name = real_names.get(name, name) docname = tree_prefix + name if docname.endswith(suffix): docname = docname[:-len(suffix)] docname = posixpath.normpath(posixpath.join(dirname, docname)) if docname not in env.found_docs: warnings.append(state.document.reporter.warning( 'toctree references unknown document %r' % docname, line=lineno)) docnames.append(docname) tocnode = sphinx.addnodes.toctree() tocnode['includefiles'] = docnames tocnode['maxdepth'] = -1 tocnode['glob'] = None tocnode['entries'] = [(None, docname) for docname in docnames] tocnode = autosummary_toc('', '', tocnode) return warnings + [node] + [tocnode] else: return warnings + [node] def get_autosummary(names, state, no_signatures=False): """ Generate a proper table node for autosummary:: directive. Parameters ---------- names : list of str Names of Python objects to be imported and added to the table. document : document Docutils document object """ document = state.document real_names = {} warnings = [] prefixes = [''] prefixes.insert(0, document.settings.env.currmodule) table = nodes.table('') group = nodes.tgroup('', cols=2) table.append(group) group.append(nodes.colspec('', colwidth=10)) group.append(nodes.colspec('', colwidth=90)) body = nodes.tbody('') group.append(body) def append_row(*column_texts): row = nodes.row('') for text in column_texts: node = nodes.paragraph('') vl = ViewList() vl.append(text, '<autosummary>') state.nested_parse(vl, 0, node) try: if isinstance(node[0], nodes.paragraph): node = node[0] except IndexError: pass row.append(nodes.entry('', node)) body.append(row) for name in names: try: obj, real_name = import_by_name(name, prefixes=prefixes) except ImportError: warnings.append(document.reporter.warning( 'failed to import %s' % name)) append_row(":obj:`%s`" % name, "") continue real_names[name] = real_name doc = get_doc_object(obj) if doc['Summary']: title = " ".join(doc['Summary']) else: title = "" col1 = u":obj:`%s <%s>`" % (name, real_name) if doc['Signature']: sig = re.sub('^[^(\[]*', '', doc['Signature'].strip()) if '=' in sig: # abbreviate optional arguments sig = re.sub(r', ([a-zA-Z0-9_]+)=', r'[, \1=', sig, count=1) sig = re.sub(r'\(([a-zA-Z0-9_]+)=', r'([\1=', sig, count=1) sig = re.sub(r'=[^,)]+,', ',', sig) sig = re.sub(r'=[^,)]+\)$', '])', sig) # shorten long strings sig = re.sub(r'(\[.{16,16}[^,]*?),.*?\]\)', r'\1, ...])', sig) else: sig = re.sub(r'(\(.{16,16}[^,]*?),.*?\)', r'\1, ...)', sig) # make signature contain non-breaking spaces col1 += u"\\ \u00a0" + unicode(sig).replace(u" ", u"\u00a0") col2 = title append_row(col1, col2) return table, warnings, real_names def import_by_name(name, prefixes=[None]): """ Import a Python object that has the given name, under one of the prefixes. Parameters ---------- name : str Name of a Python object, eg. 'numpy.ndarray.view' prefixes : list of (str or None), optional Prefixes to prepend to the name (None implies no prefix). The first prefixed name that results to successful import is used. Returns ------- obj The imported object name Name of the imported object (useful if `prefixes` was used) """ for prefix in prefixes: try: if prefix: prefixed_name = '.'.join([prefix, name]) else: prefixed_name = name return _import_by_name(prefixed_name), prefixed_name except ImportError: pass raise ImportError def _import_by_name(name): """Import a Python object given its full name""" try: # try first interpret `name` as MODNAME.OBJ name_parts = name.split('.') try: modname = '.'.join(name_parts[:-1]) __import__(modname) return getattr(sys.modules[modname], name_parts[-1]) except (ImportError, IndexError, AttributeError): pass # ... then as MODNAME, MODNAME.OBJ1, MODNAME.OBJ1.OBJ2, ... last_j = 0 modname = None for j in reversed(range(1, len(name_parts)+1)): last_j = j modname = '.'.join(name_parts[:j]) try: __import__(modname) except ImportError: continue if modname in sys.modules: break if last_j < len(name_parts): obj = sys.modules[modname] for obj_name in name_parts[last_j:]: obj = getattr(obj, obj_name) return obj else: return sys.modules[modname] except (ValueError, ImportError, AttributeError, KeyError), e: raise ImportError(e) #------------------------------------------------------------------------------ # :autolink: (smart default role) #------------------------------------------------------------------------------ def autolink_role(typ, rawtext, etext, lineno, inliner, options={}, content=[]): """ Smart linking role. Expands to ":obj:`text`" if `text` is an object that can be imported; otherwise expands to "*text*". """ r = sphinx.roles.xfileref_role('obj', rawtext, etext, lineno, inliner, options, content) pnode = r[0][0] prefixes = [None] #prefixes.insert(0, inliner.document.settings.env.currmodule) try: obj, name = import_by_name(pnode['reftarget'], prefixes) except ImportError: content = pnode[0] r[0][0] = nodes.emphasis(rawtext, content[0].astext(), classes=content['classes']) return r
11ghenrylv-mongotest
doc/sphinxext/numpydoc/autosummary.py
Python
lgpl
11,412
#!/usr/bin/env python r""" autosummary_generate.py OPTIONS FILES Generate automatic RST source files for items referred to in autosummary:: directives. Each generated RST file contains a single auto*:: directive which extracts the docstring of the referred item. Example Makefile rule:: generate: ./ext/autosummary_generate.py -o source/generated source/*.rst """ import glob, re, inspect, os, optparse, pydoc from autosummary import import_by_name try: from phantom_import import import_phantom_module except ImportError: import_phantom_module = lambda x: x def main(): p = optparse.OptionParser(__doc__.strip()) p.add_option("-p", "--phantom", action="store", type="string", dest="phantom", default=None, help="Phantom import modules from a file") p.add_option("-o", "--output-dir", action="store", type="string", dest="output_dir", default=None, help=("Write all output files to the given directory (instead " "of writing them as specified in the autosummary:: " "directives)")) options, args = p.parse_args() if len(args) == 0: p.error("wrong number of arguments") if options.phantom and os.path.isfile(options.phantom): import_phantom_module(options.phantom) # read names = {} for name, loc in get_documented(args).items(): for (filename, sec_title, keyword, toctree) in loc: if toctree is not None: path = os.path.join(os.path.dirname(filename), toctree) names[name] = os.path.abspath(path) # write for name, path in sorted(names.items()): if options.output_dir is not None: path = options.output_dir if not os.path.isdir(path): os.makedirs(path) try: obj, name = import_by_name(name) except ImportError, e: print "Failed to import '%s': %s" % (name, e) continue fn = os.path.join(path, '%s.rst' % name) if os.path.exists(fn): # skip continue f = open(fn, 'w') try: f.write('%s\n%s\n\n' % (name, '='*len(name))) if inspect.isclass(obj): if issubclass(obj, Exception): f.write(format_modulemember(name, 'autoexception')) else: f.write(format_modulemember(name, 'autoclass')) elif inspect.ismodule(obj): f.write(format_modulemember(name, 'automodule')) elif inspect.ismethod(obj) or inspect.ismethoddescriptor(obj): f.write(format_classmember(name, 'automethod')) elif callable(obj): f.write(format_modulemember(name, 'autofunction')) elif hasattr(obj, '__get__'): f.write(format_classmember(name, 'autoattribute')) else: f.write(format_modulemember(name, 'autofunction')) finally: f.close() def format_modulemember(name, directive): parts = name.split('.') mod, name = '.'.join(parts[:-1]), parts[-1] return ".. currentmodule:: %s\n\n.. %s:: %s\n" % (mod, directive, name) def format_classmember(name, directive): parts = name.split('.') mod, name = '.'.join(parts[:-2]), '.'.join(parts[-2:]) return ".. currentmodule:: %s\n\n.. %s:: %s\n" % (mod, directive, name) def get_documented(filenames): """ Find out what items are documented in source/*.rst See `get_documented_in_lines`. """ documented = {} for filename in filenames: f = open(filename, 'r') lines = f.read().splitlines() documented.update(get_documented_in_lines(lines, filename=filename)) f.close() return documented def get_documented_in_docstring(name, module=None, filename=None): """ Find out what items are documented in the given object's docstring. See `get_documented_in_lines`. """ try: obj, real_name = import_by_name(name) lines = pydoc.getdoc(obj).splitlines() return get_documented_in_lines(lines, module=name, filename=filename) except AttributeError: pass except ImportError, e: print "Failed to import '%s': %s" % (name, e) return {} def get_documented_in_lines(lines, module=None, filename=None): """ Find out what items are documented in the given lines Returns ------- documented : dict of list of (filename, title, keyword, toctree) Dictionary whose keys are documented names of objects. The value is a list of locations where the object was documented. Each location is a tuple of filename, the current section title, the name of the directive, and the value of the :toctree: argument (if present) of the directive. """ title_underline_re = re.compile("^[-=*_^#]{3,}\s*$") autodoc_re = re.compile(".. auto(function|method|attribute|class|exception|module)::\s*([A-Za-z0-9_.]+)\s*$") autosummary_re = re.compile(r'^\.\.\s+autosummary::\s*') module_re = re.compile(r'^\.\.\s+(current)?module::\s*([a-zA-Z0-9_.]+)\s*$') autosummary_item_re = re.compile(r'^\s+([_a-zA-Z][a-zA-Z0-9_.]*)\s*.*?') toctree_arg_re = re.compile(r'^\s+:toctree:\s*(.*?)\s*$') documented = {} current_title = [] last_line = None toctree = None current_module = module in_autosummary = False for line in lines: try: if in_autosummary: m = toctree_arg_re.match(line) if m: toctree = m.group(1) continue if line.strip().startswith(':'): continue # skip options m = autosummary_item_re.match(line) if m: name = m.group(1).strip() if current_module and not name.startswith(current_module + '.'): name = "%s.%s" % (current_module, name) documented.setdefault(name, []).append( (filename, current_title, 'autosummary', toctree)) continue if line.strip() == '': continue in_autosummary = False m = autosummary_re.match(line) if m: in_autosummary = True continue m = autodoc_re.search(line) if m: name = m.group(2).strip() if m.group(1) == "module": current_module = name documented.update(get_documented_in_docstring( name, filename=filename)) elif current_module and not name.startswith(current_module+'.'): name = "%s.%s" % (current_module, name) documented.setdefault(name, []).append( (filename, current_title, "auto" + m.group(1), None)) continue m = title_underline_re.match(line) if m and last_line: current_title = last_line.strip() continue m = module_re.match(line) if m: current_module = m.group(2) continue finally: last_line = line return documented if __name__ == "__main__": main()
11ghenrylv-mongotest
doc/sphinxext/numpydoc/autosummary_generate.py
Python
lgpl
7,484
from distutils.core import setup import setuptools import sys, os version = "0.2.dev" setup( name="numpydoc", packages=["numpydoc"], package_dir={"numpydoc": ""}, version=version, description="Sphinx extension to support docstrings in Numpy format", # classifiers from http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=["Development Status :: 3 - Alpha", "Environment :: Plugins", "License :: OSI Approved :: BSD License", "Topic :: Documentation"], keywords="sphinx numpy", author="Pauli Virtanen and others", author_email="pav@iki.fi", url="http://projects.scipy.org/numpy/browser/trunk/doc/sphinxext", license="BSD", zip_safe=False, install_requires=["Sphinx >= 0.5"], package_data={'numpydoc': 'tests'}, entry_points={ "console_scripts": [ "autosummary_generate = numpydoc.autosummary_generate:main", ], }, )
11ghenrylv-mongotest
doc/sphinxext/numpydoc/setup.py
Python
lgpl
979
""" Turn compiler.ast structures back into executable python code. The unparse method takes a compiler.ast tree and transforms it back into valid python code. It is incomplete and currently only works for import statements, function calls, function definitions, assignments, and basic expressions. Inspired by python-2.5-svn/Demo/parser/unparse.py fixme: We may want to move to using _ast trees because the compiler for them is about 6 times faster than compiler.compile. """ import sys import cStringIO from compiler.ast import Const, Name, Tuple, Div, Mul, Sub, Add def unparse(ast, single_line_functions=False): s = cStringIO.StringIO() UnparseCompilerAst(ast, s, single_line_functions) return s.getvalue().lstrip() op_precedence = { 'compiler.ast.Power':3, 'compiler.ast.Mul':2, 'compiler.ast.Div':2, 'compiler.ast.Add':1, 'compiler.ast.Sub':1 } class UnparseCompilerAst: """ Methods in this class recursively traverse an AST and output source code for the abstract syntax; original formatting is disregarged. """ ######################################################################### # object interface. ######################################################################### def __init__(self, tree, file = sys.stdout, single_line_functions=False): """ Unparser(tree, file=sys.stdout) -> None. Print the source for tree to file. """ self.f = file self._single_func = single_line_functions self._do_indent = True self._indent = 0 self._dispatch(tree) self._write("\n") self.f.flush() ######################################################################### # Unparser private interface. ######################################################################### ### format, output, and dispatch methods ################################ def _fill(self, text = ""): "Indent a piece of text, according to the current indentation level" if self._do_indent: self._write("\n"+" "*self._indent + text) else: self._write(text) def _write(self, text): "Append a piece of text to the current line." self.f.write(text) def _enter(self): "Print ':', and increase the indentation." self._write(": ") self._indent += 1 def _leave(self): "Decrease the indentation level." self._indent -= 1 def _dispatch(self, tree): "_dispatcher function, _dispatching tree type T to method _T." if isinstance(tree, list): for t in tree: self._dispatch(t) return meth = getattr(self, "_"+tree.__class__.__name__) if tree.__class__.__name__ == 'NoneType' and not self._do_indent: return meth(tree) ######################################################################### # compiler.ast unparsing methods. # # There should be one method per concrete grammar type. They are # organized in alphabetical order. ######################################################################### def _Add(self, t): self.__binary_op(t, '+') def _And(self, t): self._write(" (") for i, node in enumerate(t.nodes): self._dispatch(node) if i != len(t.nodes)-1: self._write(") and (") self._write(")") def _AssAttr(self, t): """ Handle assigning an attribute of an object """ self._dispatch(t.expr) self._write('.'+t.attrname) def _Assign(self, t): """ Expression Assignment such as "a = 1". This only handles assignment in expressions. Keyword assignment is handled separately. """ self._fill() for target in t.nodes: self._dispatch(target) self._write(" = ") self._dispatch(t.expr) if not self._do_indent: self._write('; ') def _AssName(self, t): """ Name on left hand side of expression. Treat just like a name on the right side of an expression. """ self._Name(t) def _AssTuple(self, t): """ Tuple on left hand side of an expression. """ # _write each elements, separated by a comma. for element in t.nodes[:-1]: self._dispatch(element) self._write(", ") # Handle the last one without writing comma last_element = t.nodes[-1] self._dispatch(last_element) def _AugAssign(self, t): """ +=,-=,*=,/=,**=, etc. operations """ self._fill() self._dispatch(t.node) self._write(' '+t.op+' ') self._dispatch(t.expr) if not self._do_indent: self._write(';') def _Bitand(self, t): """ Bit and operation. """ for i, node in enumerate(t.nodes): self._write("(") self._dispatch(node) self._write(")") if i != len(t.nodes)-1: self._write(" & ") def _Bitor(self, t): """ Bit or operation """ for i, node in enumerate(t.nodes): self._write("(") self._dispatch(node) self._write(")") if i != len(t.nodes)-1: self._write(" | ") def _CallFunc(self, t): """ Function call. """ self._dispatch(t.node) self._write("(") comma = False for e in t.args: if comma: self._write(", ") else: comma = True self._dispatch(e) if t.star_args: if comma: self._write(", ") else: comma = True self._write("*") self._dispatch(t.star_args) if t.dstar_args: if comma: self._write(", ") else: comma = True self._write("**") self._dispatch(t.dstar_args) self._write(")") def _Compare(self, t): self._dispatch(t.expr) for op, expr in t.ops: self._write(" " + op + " ") self._dispatch(expr) def _Const(self, t): """ A constant value such as an integer value, 3, or a string, "hello". """ self._dispatch(t.value) def _Decorators(self, t): """ Handle function decorators (eg. @has_units) """ for node in t.nodes: self._dispatch(node) def _Dict(self, t): self._write("{") for i, (k, v) in enumerate(t.items): self._dispatch(k) self._write(": ") self._dispatch(v) if i < len(t.items)-1: self._write(", ") self._write("}") def _Discard(self, t): """ Node for when return value is ignored such as in "foo(a)". """ self._fill() self._dispatch(t.expr) def _Div(self, t): self.__binary_op(t, '/') def _Ellipsis(self, t): self._write("...") def _From(self, t): """ Handle "from xyz import foo, bar as baz". """ # fixme: Are From and ImportFrom handled differently? self._fill("from ") self._write(t.modname) self._write(" import ") for i, (name,asname) in enumerate(t.names): if i != 0: self._write(", ") self._write(name) if asname is not None: self._write(" as "+asname) def _Function(self, t): """ Handle function definitions """ if t.decorators is not None: self._fill("@") self._dispatch(t.decorators) self._fill("def "+t.name + "(") defaults = [None] * (len(t.argnames) - len(t.defaults)) + list(t.defaults) for i, arg in enumerate(zip(t.argnames, defaults)): self._write(arg[0]) if arg[1] is not None: self._write('=') self._dispatch(arg[1]) if i < len(t.argnames)-1: self._write(', ') self._write(")") if self._single_func: self._do_indent = False self._enter() self._dispatch(t.code) self._leave() self._do_indent = True def _Getattr(self, t): """ Handle getting an attribute of an object """ if isinstance(t.expr, (Div, Mul, Sub, Add)): self._write('(') self._dispatch(t.expr) self._write(')') else: self._dispatch(t.expr) self._write('.'+t.attrname) def _If(self, t): self._fill() for i, (compare,code) in enumerate(t.tests): if i == 0: self._write("if ") else: self._write("elif ") self._dispatch(compare) self._enter() self._fill() self._dispatch(code) self._leave() self._write("\n") if t.else_ is not None: self._write("else") self._enter() self._fill() self._dispatch(t.else_) self._leave() self._write("\n") def _IfExp(self, t): self._dispatch(t.then) self._write(" if ") self._dispatch(t.test) if t.else_ is not None: self._write(" else (") self._dispatch(t.else_) self._write(")") def _Import(self, t): """ Handle "import xyz.foo". """ self._fill("import ") for i, (name,asname) in enumerate(t.names): if i != 0: self._write(", ") self._write(name) if asname is not None: self._write(" as "+asname) def _Keyword(self, t): """ Keyword value assignment within function calls and definitions. """ self._write(t.name) self._write("=") self._dispatch(t.expr) def _List(self, t): self._write("[") for i,node in enumerate(t.nodes): self._dispatch(node) if i < len(t.nodes)-1: self._write(", ") self._write("]") def _Module(self, t): if t.doc is not None: self._dispatch(t.doc) self._dispatch(t.node) def _Mul(self, t): self.__binary_op(t, '*') def _Name(self, t): self._write(t.name) def _NoneType(self, t): self._write("None") def _Not(self, t): self._write('not (') self._dispatch(t.expr) self._write(')') def _Or(self, t): self._write(" (") for i, node in enumerate(t.nodes): self._dispatch(node) if i != len(t.nodes)-1: self._write(") or (") self._write(")") def _Pass(self, t): self._write("pass\n") def _Printnl(self, t): self._fill("print ") if t.dest: self._write(">> ") self._dispatch(t.dest) self._write(", ") comma = False for node in t.nodes: if comma: self._write(', ') else: comma = True self._dispatch(node) def _Power(self, t): self.__binary_op(t, '**') def _Return(self, t): self._fill("return ") if t.value: if isinstance(t.value, Tuple): text = ', '.join([ name.name for name in t.value.asList() ]) self._write(text) else: self._dispatch(t.value) if not self._do_indent: self._write('; ') def _Slice(self, t): self._dispatch(t.expr) self._write("[") if t.lower: self._dispatch(t.lower) self._write(":") if t.upper: self._dispatch(t.upper) #if t.step: # self._write(":") # self._dispatch(t.step) self._write("]") def _Sliceobj(self, t): for i, node in enumerate(t.nodes): if i != 0: self._write(":") if not (isinstance(node, Const) and node.value is None): self._dispatch(node) def _Stmt(self, tree): for node in tree.nodes: self._dispatch(node) def _Sub(self, t): self.__binary_op(t, '-') def _Subscript(self, t): self._dispatch(t.expr) self._write("[") for i, value in enumerate(t.subs): if i != 0: self._write(",") self._dispatch(value) self._write("]") def _TryExcept(self, t): self._fill("try") self._enter() self._dispatch(t.body) self._leave() for handler in t.handlers: self._fill('except ') self._dispatch(handler[0]) if handler[1] is not None: self._write(', ') self._dispatch(handler[1]) self._enter() self._dispatch(handler[2]) self._leave() if t.else_: self._fill("else") self._enter() self._dispatch(t.else_) self._leave() def _Tuple(self, t): if not t.nodes: # Empty tuple. self._write("()") else: self._write("(") # _write each elements, separated by a comma. for element in t.nodes[:-1]: self._dispatch(element) self._write(", ") # Handle the last one without writing comma last_element = t.nodes[-1] self._dispatch(last_element) self._write(")") def _UnaryAdd(self, t): self._write("+") self._dispatch(t.expr) def _UnarySub(self, t): self._write("-") self._dispatch(t.expr) def _With(self, t): self._fill('with ') self._dispatch(t.expr) if t.vars: self._write(' as ') self._dispatch(t.vars.name) self._enter() self._dispatch(t.body) self._leave() self._write('\n') def _int(self, t): self._write(repr(t)) def __binary_op(self, t, symbol): # Check if parenthesis are needed on left side and then dispatch has_paren = False left_class = str(t.left.__class__) if (left_class in op_precedence.keys() and op_precedence[left_class] < op_precedence[str(t.__class__)]): has_paren = True if has_paren: self._write('(') self._dispatch(t.left) if has_paren: self._write(')') # Write the appropriate symbol for operator self._write(symbol) # Check if parenthesis are needed on the right side and then dispatch has_paren = False right_class = str(t.right.__class__) if (right_class in op_precedence.keys() and op_precedence[right_class] < op_precedence[str(t.__class__)]): has_paren = True if has_paren: self._write('(') self._dispatch(t.right) if has_paren: self._write(')') def _float(self, t): # if t is 0.1, str(t)->'0.1' while repr(t)->'0.1000000000001' # We prefer str here. self._write(str(t)) def _str(self, t): self._write(repr(t)) def _tuple(self, t): self._write(str(t)) ######################################################################### # These are the methods from the _ast modules unparse. # # As our needs to handle more advanced code increase, we may want to # modify some of the methods below so that they work for compiler.ast. ######################################################################### # # stmt # def _Expr(self, tree): # self._fill() # self._dispatch(tree.value) # # def _Import(self, t): # self._fill("import ") # first = True # for a in t.names: # if first: # first = False # else: # self._write(", ") # self._write(a.name) # if a.asname: # self._write(" as "+a.asname) # ## def _ImportFrom(self, t): ## self._fill("from ") ## self._write(t.module) ## self._write(" import ") ## for i, a in enumerate(t.names): ## if i == 0: ## self._write(", ") ## self._write(a.name) ## if a.asname: ## self._write(" as "+a.asname) ## # XXX(jpe) what is level for? ## # # def _Break(self, t): # self._fill("break") # # def _Continue(self, t): # self._fill("continue") # # def _Delete(self, t): # self._fill("del ") # self._dispatch(t.targets) # # def _Assert(self, t): # self._fill("assert ") # self._dispatch(t.test) # if t.msg: # self._write(", ") # self._dispatch(t.msg) # # def _Exec(self, t): # self._fill("exec ") # self._dispatch(t.body) # if t.globals: # self._write(" in ") # self._dispatch(t.globals) # if t.locals: # self._write(", ") # self._dispatch(t.locals) # # def _Print(self, t): # self._fill("print ") # do_comma = False # if t.dest: # self._write(">>") # self._dispatch(t.dest) # do_comma = True # for e in t.values: # if do_comma:self._write(", ") # else:do_comma=True # self._dispatch(e) # if not t.nl: # self._write(",") # # def _Global(self, t): # self._fill("global") # for i, n in enumerate(t.names): # if i != 0: # self._write(",") # self._write(" " + n) # # def _Yield(self, t): # self._fill("yield") # if t.value: # self._write(" (") # self._dispatch(t.value) # self._write(")") # # def _Raise(self, t): # self._fill('raise ') # if t.type: # self._dispatch(t.type) # if t.inst: # self._write(", ") # self._dispatch(t.inst) # if t.tback: # self._write(", ") # self._dispatch(t.tback) # # # def _TryFinally(self, t): # self._fill("try") # self._enter() # self._dispatch(t.body) # self._leave() # # self._fill("finally") # self._enter() # self._dispatch(t.finalbody) # self._leave() # # def _excepthandler(self, t): # self._fill("except ") # if t.type: # self._dispatch(t.type) # if t.name: # self._write(", ") # self._dispatch(t.name) # self._enter() # self._dispatch(t.body) # self._leave() # # def _ClassDef(self, t): # self._write("\n") # self._fill("class "+t.name) # if t.bases: # self._write("(") # for a in t.bases: # self._dispatch(a) # self._write(", ") # self._write(")") # self._enter() # self._dispatch(t.body) # self._leave() # # def _FunctionDef(self, t): # self._write("\n") # for deco in t.decorators: # self._fill("@") # self._dispatch(deco) # self._fill("def "+t.name + "(") # self._dispatch(t.args) # self._write(")") # self._enter() # self._dispatch(t.body) # self._leave() # # def _For(self, t): # self._fill("for ") # self._dispatch(t.target) # self._write(" in ") # self._dispatch(t.iter) # self._enter() # self._dispatch(t.body) # self._leave() # if t.orelse: # self._fill("else") # self._enter() # self._dispatch(t.orelse) # self._leave # # def _While(self, t): # self._fill("while ") # self._dispatch(t.test) # self._enter() # self._dispatch(t.body) # self._leave() # if t.orelse: # self._fill("else") # self._enter() # self._dispatch(t.orelse) # self._leave # # # expr # def _Str(self, tree): # self._write(repr(tree.s)) ## # def _Repr(self, t): # self._write("`") # self._dispatch(t.value) # self._write("`") # # def _Num(self, t): # self._write(repr(t.n)) # # def _ListComp(self, t): # self._write("[") # self._dispatch(t.elt) # for gen in t.generators: # self._dispatch(gen) # self._write("]") # # def _GeneratorExp(self, t): # self._write("(") # self._dispatch(t.elt) # for gen in t.generators: # self._dispatch(gen) # self._write(")") # # def _comprehension(self, t): # self._write(" for ") # self._dispatch(t.target) # self._write(" in ") # self._dispatch(t.iter) # for if_clause in t.ifs: # self._write(" if ") # self._dispatch(if_clause) # # def _IfExp(self, t): # self._dispatch(t.body) # self._write(" if ") # self._dispatch(t.test) # if t.orelse: # self._write(" else ") # self._dispatch(t.orelse) # # unop = {"Invert":"~", "Not": "not", "UAdd":"+", "USub":"-"} # def _UnaryOp(self, t): # self._write(self.unop[t.op.__class__.__name__]) # self._write("(") # self._dispatch(t.operand) # self._write(")") # # binop = { "Add":"+", "Sub":"-", "Mult":"*", "Div":"/", "Mod":"%", # "LShift":">>", "RShift":"<<", "BitOr":"|", "BitXor":"^", "BitAnd":"&", # "FloorDiv":"//", "Pow": "**"} # def _BinOp(self, t): # self._write("(") # self._dispatch(t.left) # self._write(")" + self.binop[t.op.__class__.__name__] + "(") # self._dispatch(t.right) # self._write(")") # # boolops = {_ast.And: 'and', _ast.Or: 'or'} # def _BoolOp(self, t): # self._write("(") # self._dispatch(t.values[0]) # for v in t.values[1:]: # self._write(" %s " % self.boolops[t.op.__class__]) # self._dispatch(v) # self._write(")") # # def _Attribute(self,t): # self._dispatch(t.value) # self._write(".") # self._write(t.attr) # ## def _Call(self, t): ## self._dispatch(t.func) ## self._write("(") ## comma = False ## for e in t.args: ## if comma: self._write(", ") ## else: comma = True ## self._dispatch(e) ## for e in t.keywords: ## if comma: self._write(", ") ## else: comma = True ## self._dispatch(e) ## if t.starargs: ## if comma: self._write(", ") ## else: comma = True ## self._write("*") ## self._dispatch(t.starargs) ## if t.kwargs: ## if comma: self._write(", ") ## else: comma = True ## self._write("**") ## self._dispatch(t.kwargs) ## self._write(")") # # # slice # def _Index(self, t): # self._dispatch(t.value) # # def _ExtSlice(self, t): # for i, d in enumerate(t.dims): # if i != 0: # self._write(': ') # self._dispatch(d) # # # others # def _arguments(self, t): # first = True # nonDef = len(t.args)-len(t.defaults) # for a in t.args[0:nonDef]: # if first:first = False # else: self._write(", ") # self._dispatch(a) # for a,d in zip(t.args[nonDef:], t.defaults): # if first:first = False # else: self._write(", ") # self._dispatch(a), # self._write("=") # self._dispatch(d) # if t.vararg: # if first:first = False # else: self._write(", ") # self._write("*"+t.vararg) # if t.kwarg: # if first:first = False # else: self._write(", ") # self._write("**"+t.kwarg) # ## def _keyword(self, t): ## self._write(t.arg) ## self._write("=") ## self._dispatch(t.value) # # def _Lambda(self, t): # self._write("lambda ") # self._dispatch(t.args) # self._write(": ") # self._dispatch(t.body)
11ghenrylv-mongotest
doc/sphinxext/numpydoc/compiler_unparse.py
Python
lgpl
24,704
""" ============== phantom_import ============== Sphinx extension to make directives from ``sphinx.ext.autodoc`` and similar extensions to use docstrings loaded from an XML file. This extension loads an XML file in the Pydocweb format [1] and creates a dummy module that contains the specified docstrings. This can be used to get the current docstrings from a Pydocweb instance without needing to rebuild the documented module. .. [1] http://code.google.com/p/pydocweb """ import imp, sys, compiler, types, os, inspect, re def setup(app): app.connect('builder-inited', initialize) app.add_config_value('phantom_import_file', None, True) def initialize(app): fn = app.config.phantom_import_file if (fn and os.path.isfile(fn)): print "[numpydoc] Phantom importing modules from", fn, "..." import_phantom_module(fn) #------------------------------------------------------------------------------ # Creating 'phantom' modules from an XML description #------------------------------------------------------------------------------ def import_phantom_module(xml_file): """ Insert a fake Python module to sys.modules, based on a XML file. The XML file is expected to conform to Pydocweb DTD. The fake module will contain dummy objects, which guarantee the following: - Docstrings are correct. - Class inheritance relationships are correct (if present in XML). - Function argspec is *NOT* correct (even if present in XML). Instead, the function signature is prepended to the function docstring. - Class attributes are *NOT* correct; instead, they are dummy objects. Parameters ---------- xml_file : str Name of an XML file to read """ import lxml.etree as etree object_cache = {} tree = etree.parse(xml_file) root = tree.getroot() # Sort items so that # - Base classes come before classes inherited from them # - Modules come before their contents all_nodes = dict([(n.attrib['id'], n) for n in root]) def _get_bases(node, recurse=False): bases = [x.attrib['ref'] for x in node.findall('base')] if recurse: j = 0 while True: try: b = bases[j] except IndexError: break if b in all_nodes: bases.extend(_get_bases(all_nodes[b])) j += 1 return bases type_index = ['module', 'class', 'callable', 'object'] def base_cmp(a, b): x = cmp(type_index.index(a.tag), type_index.index(b.tag)) if x != 0: return x if a.tag == 'class' and b.tag == 'class': a_bases = _get_bases(a, recurse=True) b_bases = _get_bases(b, recurse=True) x = cmp(len(a_bases), len(b_bases)) if x != 0: return x if a.attrib['id'] in b_bases: return -1 if b.attrib['id'] in a_bases: return 1 return cmp(a.attrib['id'].count('.'), b.attrib['id'].count('.')) nodes = root.getchildren() nodes.sort(base_cmp) # Create phantom items for node in nodes: name = node.attrib['id'] doc = (node.text or '').decode('string-escape') + "\n" if doc == "\n": doc = "" # create parent, if missing parent = name while True: parent = '.'.join(parent.split('.')[:-1]) if not parent: break if parent in object_cache: break obj = imp.new_module(parent) object_cache[parent] = obj sys.modules[parent] = obj # create object if node.tag == 'module': obj = imp.new_module(name) obj.__doc__ = doc sys.modules[name] = obj elif node.tag == 'class': bases = [object_cache[b] for b in _get_bases(node) if b in object_cache] bases.append(object) init = lambda self: None init.__doc__ = doc obj = type(name, tuple(bases), {'__doc__': doc, '__init__': init}) obj.__name__ = name.split('.')[-1] elif node.tag == 'callable': funcname = node.attrib['id'].split('.')[-1] argspec = node.attrib.get('argspec') if argspec: argspec = re.sub('^[^(]*', '', argspec) doc = "%s%s\n\n%s" % (funcname, argspec, doc) obj = lambda: 0 obj.__argspec_is_invalid_ = True obj.func_name = funcname obj.__name__ = name obj.__doc__ = doc if inspect.isclass(object_cache[parent]): obj.__objclass__ = object_cache[parent] else: class Dummy(object): pass obj = Dummy() obj.__name__ = name obj.__doc__ = doc if inspect.isclass(object_cache[parent]): obj.__get__ = lambda: None object_cache[name] = obj if parent: if inspect.ismodule(object_cache[parent]): obj.__module__ = parent setattr(object_cache[parent], name.split('.')[-1], obj) # Populate items for node in root: obj = object_cache.get(node.attrib['id']) if obj is None: continue for ref in node.findall('ref'): if node.tag == 'class': if ref.attrib['ref'].startswith(node.attrib['id'] + '.'): setattr(obj, ref.attrib['name'], object_cache.get(ref.attrib['ref'])) else: setattr(obj, ref.attrib['name'], object_cache.get(ref.attrib['ref']))
11ghenrylv-mongotest
doc/sphinxext/numpydoc/phantom_import.py
Python
lgpl
5,684
from numpydoc import setup
11ghenrylv-mongotest
doc/sphinxext/numpydoc/__init__.py
Python
lgpl
27
import re, inspect, textwrap, pydoc import sphinx from docscrape import NumpyDocString, FunctionDoc, ClassDoc class SphinxDocString(NumpyDocString): # string conversion routines def _str_header(self, name, symbol='`'): return ['.. rubric:: ' + name, ''] def _str_field_list(self, name): return [':' + name + ':'] def _str_indent(self, doc, indent=4): out = [] for line in doc: out += [' '*indent + line] return out def _str_signature(self): return [''] if self['Signature']: return ['``%s``' % self['Signature']] + [''] else: return [''] def _str_summary(self): return self['Summary'] + [''] def _str_extended_summary(self): return self['Extended Summary'] + [''] def _str_param_list(self, name): out = [] if self[name]: out += self._str_field_list(name) out += [''] for param,param_type,desc in self[name]: out += self._str_indent(['**%s** : %s' % (param.strip(), param_type)]) out += [''] out += self._str_indent(desc,8) out += [''] return out def _str_section(self, name): out = [] if self[name]: out += self._str_header(name) out += [''] content = textwrap.dedent("\n".join(self[name])).split("\n") out += content out += [''] return out def _str_see_also(self, func_role): out = [] if self['See Also']: see_also = super(SphinxDocString, self)._str_see_also(func_role) out = ['.. seealso::', ''] out += self._str_indent(see_also[2:]) return out def _str_warnings(self): out = [] if self['Warnings']: out = ['.. warning::', ''] out += self._str_indent(self['Warnings']) return out def _str_index(self): idx = self['index'] out = [] if len(idx) == 0: return out out += ['.. index:: %s' % idx.get('default','')] for section, references in idx.iteritems(): if section == 'default': continue elif section == 'refguide': out += [' single: %s' % (', '.join(references))] else: out += [' %s: %s' % (section, ','.join(references))] return out def _str_references(self): out = [] if self['References']: out += self._str_header('References') if isinstance(self['References'], str): self['References'] = [self['References']] out.extend(self['References']) out += [''] # Latex collects all references to a separate bibliography, # so we need to insert links to it if sphinx.__version__ >= 0.6: out += ['.. only:: latex',''] else: out += ['.. latexonly::',''] items = [] for line in self['References']: m = re.match(r'.. \[([a-z0-9._-]+)\]', line, re.I) if m: items.append(m.group(1)) out += [' ' + ", ".join(["[%s]_" % item for item in items]), ''] return out def __str__(self, indent=0, func_role="obj"): out = [] out += self._str_signature() out += self._str_index() + [''] out += self._str_summary() out += self._str_extended_summary() for param_list in ('Parameters', 'Attributes', 'Methods', 'Returns','Raises'): out += self._str_param_list(param_list) out += self._str_warnings() out += self._str_see_also(func_role) out += self._str_section('Notes') out += self._str_references() out += self._str_section('Examples') out = self._str_indent(out,indent) return '\n'.join(out) class SphinxFunctionDoc(SphinxDocString, FunctionDoc): pass class SphinxClassDoc(SphinxDocString, ClassDoc): pass def get_doc_object(obj, what=None, doc=None): if what is None: if inspect.isclass(obj): what = 'class' elif inspect.ismodule(obj): what = 'module' elif callable(obj): what = 'function' else: what = 'object' if what == 'class': return SphinxClassDoc(obj, '', func_doc=SphinxFunctionDoc, doc=doc) elif what in ('function', 'method'): return SphinxFunctionDoc(obj, '', doc=doc) else: if doc is None: doc = pydoc.getdoc(obj) return SphinxDocString(doc)
11ghenrylv-mongotest
doc/sphinxext/numpydoc/docscrape_sphinx.py
Python
lgpl
4,795
""" ======== numpydoc ======== Sphinx extension that handles docstrings in the Numpy standard format. [1] It will: - Convert Parameters etc. sections to field lists. - Convert See Also section to a See also entry. - Renumber references. - Extract the signature from the docstring, if it can't be determined otherwise. .. [1] http://projects.scipy.org/numpy/wiki/CodingStyleGuidelines#docstring-standard """ import os, re, pydoc from docscrape_sphinx import get_doc_object, SphinxDocString import inspect def mangle_docstrings(app, what, name, obj, options, lines, reference_offset=[0]): if what == 'module': # Strip top title title_re = re.compile(r'^\s*[#*=]{4,}\n[a-z0-9 -]+\n[#*=]{4,}\s*', re.I|re.S) lines[:] = title_re.sub('', "\n".join(lines)).split("\n") else: doc = get_doc_object(obj, what, "\n".join(lines)) lines[:] = str(doc).split("\n") if app.config.numpydoc_edit_link and hasattr(obj, '__name__') and \ obj.__name__: if hasattr(obj, '__module__'): v = dict(full_name="%s.%s" % (obj.__module__, obj.__name__)) else: v = dict(full_name=obj.__name__) lines += ['', '.. htmlonly::', ''] lines += [' %s' % x for x in (app.config.numpydoc_edit_link % v).split("\n")] # replace reference numbers so that there are no duplicates references = [] for line in lines: line = line.strip() m = re.match(r'^.. \[([a-z0-9_.-])\]', line, re.I) if m: references.append(m.group(1)) # start renaming from the longest string, to avoid overwriting parts references.sort(key=lambda x: -len(x)) if references: for i, line in enumerate(lines): for r in references: if re.match(r'^\d+$', r): new_r = "R%d" % (reference_offset[0] + int(r)) else: new_r = "%s%d" % (r, reference_offset[0]) lines[i] = lines[i].replace('[%s]_' % r, '[%s]_' % new_r) lines[i] = lines[i].replace('.. [%s]' % r, '.. [%s]' % new_r) reference_offset[0] += len(references) def mangle_signature(app, what, name, obj, options, sig, retann): # Do not try to inspect classes that don't define `__init__` if (inspect.isclass(obj) and 'initializes x; see ' in pydoc.getdoc(obj.__init__)): return '', '' if not (callable(obj) or hasattr(obj, '__argspec_is_invalid_')): return if not hasattr(obj, '__doc__'): return doc = SphinxDocString(pydoc.getdoc(obj)) if doc['Signature']: sig = re.sub("^[^(]*", "", doc['Signature']) return sig, '' def initialize(app): try: app.connect('autodoc-process-signature', mangle_signature) except: monkeypatch_sphinx_ext_autodoc() def setup(app, get_doc_object_=get_doc_object): global get_doc_object get_doc_object = get_doc_object_ app.connect('autodoc-process-docstring', mangle_docstrings) app.connect('builder-inited', initialize) app.add_config_value('numpydoc_edit_link', None, True) #------------------------------------------------------------------------------ # Monkeypatch sphinx.ext.autodoc to accept argspecless autodocs (Sphinx < 0.5) #------------------------------------------------------------------------------ def monkeypatch_sphinx_ext_autodoc(): global _original_format_signature import sphinx.ext.autodoc if sphinx.ext.autodoc.format_signature is our_format_signature: return print "[numpydoc] Monkeypatching sphinx.ext.autodoc ..." _original_format_signature = sphinx.ext.autodoc.format_signature sphinx.ext.autodoc.format_signature = our_format_signature def our_format_signature(what, obj): r = mangle_signature(None, what, None, obj, None, None, None) if r is not None: return r[0] else: return _original_format_signature(what, obj)
11ghenrylv-mongotest
doc/sphinxext/numpydoc/numpydoc.py
Python
lgpl
4,102
# run from web2py root folder because of autodoc & web2py import behaviour!!!! sphinx-build -b html -w doc/sphinx-build.log -Ea doc/source applications/examples/static/sphinx #sphinx-build -b html -w sphinx-build.log -Ea source ../applications/examples/static/sphinx
11ghenrylv-mongotest
doc/make-doc_html.sh
Shell
lgpl
267
# -*- coding: utf-8 -*- # default_application, default_controller, default_function # are used when the respective element is missing from the # (possibly rewritten) incoming URL # default_application = 'init' # ordinarily set in base routes.py default_controller = 'default' # ordinarily set in app-specific routes.py default_function = 'index' # ordinarily set in app-specific routes.py # routes_app is a tuple of tuples. The first item in each is a regexp that will # be used to match the incoming request URL. The second item in the tuple is # an applicationname. This mechanism allows you to specify the use of an # app-specific routes.py. This entry is meaningful only in the base routes.py. # # Example: support welcome, admin, app and myapp, with myapp the default: routes_app = ((r'/(?P<app>welcome|admin|app)\b.*', r'\g<app>'), (r'(.*)', r'myapp'), (r'/?(.*)', r'myapp')) # routes_in is a tuple of tuples. The first item in each is a regexp that will # be used to match the incoming request URL. The second item in the tuple is # what it will be replaced with. This mechanism allows you to redirect incoming # routes to different web2py locations # # Example: If you wish for your entire website to use init's static directory: # # routes_in=( (r'/static/(?P<file>[\w./-]+)', r'/init/static/\g<file>') ) # BASE = '' # optonal prefix for incoming URLs routes_in = ( # do not reroute admin unless you want to disable it (BASE + '/admin', '/admin/default/index'), (BASE + '/admin/$anything', '/admin/$anything'), # do not reroute appadmin unless you want to disable it (BASE + '/$app/appadmin', '/$app/appadmin/index'), (BASE + '/$app/appadmin/$anything', '/$app/appadmin/$anything'), # do not reroute static files (BASE + '/$app/static/$anything', '/$app/static/$anything'), # reroute favicon and robots, use exable for lack of better choice ('/favicon.ico', '/examples/static/favicon.ico'), ('/robots.txt', '/examples/static/robots.txt'), # do other stuff ((r'.*http://otherdomain.com.* (?P<any>.*)', r'/app/ctr\g<any>')), # remove the BASE prefix (BASE + '/$anything', '/$anything'), ) # routes_out, like routes_in translates URL paths created with the web2py URL() # function in the same manner that route_in translates inbound URL paths. # routes_out = ( # do not reroute admin unless you want to disable it ('/admin/$anything', BASE + '/admin/$anything'), # do not reroute appadmin unless you want to disable it ('/$app/appadmin/$anything', BASE + '/$app/appadmin/$anything'), # do not reroute static files ('/$app/static/$anything', BASE + '/$app/static/$anything'), # do other stuff (r'.*http://otherdomain.com.* /app/ctr(?P<any>.*)', r'\g<any>'), (r'/app(?P<any>.*)', r'\g<any>'), # restore the BASE prefix ('/$anything', BASE + '/$anything'), ) # Specify log level for rewrite's debug logging # Possible values: debug, info, warning, error, critical (loglevels), # off, print (print uses print statement rather than logging) # GAE users may want to use 'off' to suppress routine logging. # logging = 'debug' # Error-handling redirects all HTTP errors (status codes >= 400) to a specified # path. If you wish to use error-handling redirects, uncomment the tuple # below. You can customize responses by adding a tuple entry with the first # value in 'appName/HTTPstatusCode' format. ( Only HTTP codes >= 400 are # routed. ) and the value as a path to redirect the user to. You may also use # '*' as a wildcard. # # The error handling page is also passed the error code and ticket as # variables. Traceback information will be stored in the ticket. # # routes_onerror = [ # (r'init/400', r'/init/default/login') # ,(r'init/*', r'/init/static/fail.html') # ,(r'*/404', r'/init/static/cantfind.html') # ,(r'*/*', r'/init/error/index') # ] # specify action in charge of error handling # # error_handler = dict(application='error', # controller='default', # function='index') # In the event that the error-handling page itself returns an error, web2py will # fall back to its old static responses. You can customize them here. # ErrorMessageTicket takes a string format dictionary containing (only) the # "ticket" key. # error_message = '<html><body><h1>%s</h1></body></html>' # error_message_ticket = '<html><body><h1>Internal error</h1>Ticket issued: <a href="/admin/default/ticket/%(ticket)s" target="_blank">%(ticket)s</a></body></html>' # specify a list of apps that bypass args-checking and use request.raw_args # #routes_apps_raw=['myapp'] #routes_apps_raw=['myapp', 'myotherapp'] def __routes_doctest(): ''' Dummy function for doctesting routes.py. Use filter_url() to test incoming or outgoing routes; filter_err() for error redirection. filter_url() accepts overrides for method and remote host: filter_url(url, method='get', remote='0.0.0.0', out=False) filter_err() accepts overrides for application and ticket: filter_err(status, application='app', ticket='tkt') >>> import os >>> import gluon.main >>> from gluon.rewrite import regex_select, load, filter_url, regex_filter_out, filter_err, compile_regex >>> regex_select() >>> load(routes=os.path.basename(__file__)) >>> os.path.relpath(filter_url('http://domain.com/favicon.ico')) 'applications/examples/static/favicon.ico' >>> os.path.relpath(filter_url('http://domain.com/robots.txt')) 'applications/examples/static/robots.txt' >>> filter_url('http://domain.com') '/init/default/index' >>> filter_url('http://domain.com/') '/init/default/index' >>> filter_url('http://domain.com/init/default/fcn') '/init/default/fcn' >>> filter_url('http://domain.com/init/default/fcn/') '/init/default/fcn' >>> filter_url('http://domain.com/app/ctr/fcn') '/app/ctr/fcn' >>> filter_url('http://domain.com/app/ctr/fcn/arg1') "/app/ctr/fcn ['arg1']" >>> filter_url('http://domain.com/app/ctr/fcn/arg1/') "/app/ctr/fcn ['arg1']" >>> filter_url('http://domain.com/app/ctr/fcn/arg1//') "/app/ctr/fcn ['arg1', '']" >>> filter_url('http://domain.com/app/ctr/fcn//arg1') "/app/ctr/fcn ['', 'arg1']" >>> filter_url('HTTP://DOMAIN.COM/app/ctr/fcn') '/app/ctr/fcn' >>> filter_url('http://domain.com/app/ctr/fcn?query') '/app/ctr/fcn ?query' >>> filter_url('http://otherdomain.com/fcn') '/app/ctr/fcn' >>> regex_filter_out('/app/ctr/fcn') '/ctr/fcn' >>> filter_url('https://otherdomain.com/app/ctr/fcn', out=True) '/ctr/fcn' >>> filter_url('https://otherdomain.com/app/ctr/fcn/arg1//', out=True) '/ctr/fcn/arg1//' >>> filter_url('http://otherdomain.com/app/ctr/fcn', out=True) '/fcn' >>> filter_url('http://otherdomain.com/app/ctr/fcn?query', out=True) '/fcn?query' >>> filter_url('http://otherdomain.com/app/ctr/fcn#anchor', out=True) '/fcn#anchor' >>> filter_err(200) 200 >>> filter_err(399) 399 >>> filter_err(400) 400 >>> filter_url('http://domain.com/welcome', app=True) 'welcome' >>> filter_url('http://domain.com/', app=True) 'myapp' >>> filter_url('http://domain.com', app=True) 'myapp' >>> compile_regex('.*http://otherdomain.com.* (?P<any>.*)', '/app/ctr\g<any>')[0].pattern '^.*http://otherdomain.com.* (?P<any>.*)$' >>> compile_regex('.*http://otherdomain.com.* (?P<any>.*)', '/app/ctr\g<any>')[1] '/app/ctr\\\\g<any>' >>> compile_regex('/$c/$f', '/init/$c/$f')[0].pattern '^.*?:https?://[^:/]+:[a-z]+ /(?P<c>\\\\w+)/(?P<f>\\\\w+)$' >>> compile_regex('/$c/$f', '/init/$c/$f')[1] '/init/\\\\g<c>/\\\\g<f>' ''' pass if __name__ == '__main__': import doctest doctest.testmod()
11ghenrylv-mongotest
routes.example.py
Python
lgpl
7,899
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys if '__file__' in globals(): path = os.path.dirname(os.path.abspath(__file__)) elif hasattr(sys, 'frozen'): path = os.path.dirname(os.path.abspath(sys.executable)) # for py2exe else: # should never happen path = os.getcwd() os.chdir(path) sys.path = [path] + [p for p in sys.path if not p == path] # import gluon.import_all ##### This should be uncommented for py2exe.py import gluon.widget # Start Web2py and Web2py cron service! if __name__ == '__main__': try: from multiprocessing import freeze_support freeze_support() except: sys.stderr.write('Sorry, -K only supported for python 2.6-2.7\n') if os.environ.has_key("COVERAGE_PROCESS_START"): try: import coverage coverage.process_startup() except: pass gluon.widget.start(cron=True)
11ghenrylv-mongotest
web2py.py
Python
lgpl
914
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) """ ############################################################################## # Configuration parameters for Google App Engine ############################################################################## LOG_STATS = False # web2py level log statistics APPSTATS = True # GAE level usage statistics and profiling DEBUG = False # debug mode # # Read more about APPSTATS here # http://googleappengine.blogspot.com/2010/03/easy-performance-profiling-with.html # can be accessed from: # http://localhost:8080/_ah/stats ############################################################################## # All tricks in this file developed by Robin Bhattacharyya ############################################################################## import time import os import sys import logging import cPickle import pickle import wsgiref.handlers import datetime path = os.path.dirname(os.path.abspath(__file__)) sys.path = [path] + [p for p in sys.path if not p == path] sys.modules['cPickle'] = sys.modules['pickle'] from gluon.settings import global_settings from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app global_settings.web2py_runtime_gae = True global_settings.db_sessions = True if os.environ.get('SERVER_SOFTWARE', '').startswith('Devel'): (global_settings.web2py_runtime, DEBUG) = \ ('gae:development', True) else: (global_settings.web2py_runtime, DEBUG) = \ ('gae:production', False) import gluon.main def log_stats(fun): """Function that will act as a decorator to make logging""" def newfun(env, res): """Log the execution time of the passed function""" timer = lambda t: (t.time(), t.clock()) (t0, c0) = timer(time) executed_function = fun(env, res) (t1, c1) = timer(time) log_info = """**** Request: %.2fms/%.2fms (real time/cpu time)""" log_info = log_info % ((t1 - t0) * 1000, (c1 - c0) * 1000) logging.info(log_info) return executed_function return newfun logging.basicConfig(level=logging.INFO) def wsgiapp(env, res): """Return the wsgiapp""" env['PATH_INFO'] = env['PATH_INFO'].decode('latin1').encode('utf8') #when using the blobstore image uploader GAE dev SDK passes these as unicode # they should be regular strings as they are parts of URLs env['wsgi.url_scheme'] = str(env['wsgi.url_scheme']) env['QUERY_STRING'] = str(env['QUERY_STRING']) env['SERVER_NAME'] = str(env['SERVER_NAME']) #this deals with a problem where GAE development server seems to forget # the path between requests if global_settings.web2py_runtime == 'gae:development': gluon.admin.create_missing_folders() web2py_path = global_settings.applications_parent # backward compatibility return gluon.main.wsgibase(env, res) if LOG_STATS or DEBUG: wsgiapp = log_stats(wsgiapp) def main(): """Run the wsgi app""" run_wsgi_app(wsgiapp) if __name__ == '__main__': main()
11ghenrylv-mongotest
gaehandler.py
Python
lgpl
3,245
/* Epydoc CSS Stylesheet * * This stylesheet can be used to customize the appearance of epydoc's * HTML output. * */ /* Default Colors & Styles * - Set the default foreground & background color with 'body'; and * link colors with 'a:link' and 'a:visited'. * - Use bold for decision list terms. * - The heading styles defined here are used for headings *within* * docstring descriptions. All headings used by epydoc itself use * either class='epydoc' or class='toc' (CSS styles for both * defined below). body { background: #ffffff; color: #000000; } a:link { color: #0000ff; } a:visited { color: #204080; } dt { font-weight: bold; } h1 { font-size: +140%; font-style: italic; font-weight: bold; } h2 { font-size: +125%; font-style: italic; font-weight: bold; } h3 { font-size: +110%; font-style: italic; font-weight: normal; } code { font-size: 100%; } */ body { background-color: #fff; color: #585858; font-size: 10pt; font-family: georgia, serif; } a {color: #FF5C1F; } a:hover { text-decoration: underline; } a:visited { color: #FF5C1F;} dt { font-weight: bold; } h1 { font-size: +140%; font-style: italic; font-weight: bold; } h2 { color: #185360; font-size: +125%; font-style: italic; font-weight: bold; } h3 { color: #185360; font-size: +110%; font-style: italic; font-weight: normal; } code { font-size: 100%; } /* Page Header & Footer * - The standard page header consists of a navigation bar (with * pointers to standard pages such as 'home' and 'trees'); a * breadcrumbs list, which can be used to navigate to containing * classes or modules; options links, to show/hide private * variables and to show/hide frames; and a page title (using * <h1>). The page title may be followed by a link to the * corresponding source code (using 'span.codelink'). * - The footer consists of a navigation bar, a timestamp, and a * pointer to epydoc's homepage. h1.epydoc { margin: 0; font-size: +140%; font-weight: bold; } h2.epydoc { font-size: +130%; font-weight: bold; } h3.epydoc { font-size: +115%; font-weight: bold; } td h3.epydoc { font-size: +115%; font-weight: bold; margin-bottom: 0; } table.navbar { background: #a0c0ff; color: #000000; border: 2px groove #c0d0d0; } table.navbar table { color: #000000; } th.navbar-select { background: #70b0ff; color: #000000; } table.navbar a { text-decoration: none; } table.navbar a:link { color: #0000ff; } table.navbar a:visited { color: #204080; } span.breadcrumbs { font-size: 85%; font-weight: bold; } span.options { font-size: 70%; } span.codelink { font-size: 85%; } td.footer { font-size: 85%; } */ h1.epydoc { margin: 0; font-size: +140%; font-weight: bold; } h2.epydoc { font-size: +130%; font-weight: bold; } h3.epydoc { font-size: +115%; font-weight: bold; } td h3.epydoc { font-size: +115%; font-weight: bold; margin-bottom: 0; } table.navbar { background: url('title.png') repeat-x; #background: #a0c0ff; color: #FF5C1F; #border: 2px groove #c0d0d0; } table.navbar table { color: #FF5C1F; } th.navbar-select { background: #fff; color: #195866; } table.navbar a { text-decoration: none; color: #FF5C1F;} table.navbar a:link { color: #FF5C1F; } table.navbar a:visited { color: #FF5C1F; } span.breadcrumbs { font-size: 85%; font-weight: bold; } span.options { font-size: 70%; } span.codelink { font-size: 85%; } td.footer { font-size: 85%; } /* Table Headers * - Each summary table and details section begins with a 'header' * row. This row contains a section title (marked by * 'span.table-header') as well as a show/hide private link * (marked by 'span.options', defined above). * - Summary tables that contain user-defined groups mark those * groups using 'group header' rows. td.table-header { background: #70b0ff; color: #000000; border: 1px solid #608090; } td.table-header table { color: #000000; } td.table-header table a:link { color: #0000ff; } td.table-header table a:visited { color: #204080; } span.table-header { font-size: 120%; font-weight: bold; } th.group-header { background: #c0e0f8; color: #000000; text-align: left; font-style: italic; font-size: 115%; border: 1px solid #608090; } */ td.table-header { background: #258396; color: #000000; border: 1px solid #608090; } td.table-header table { color: #fff; } td.table-header table a:link { color: #FF5C1F; } td.table-header table a:visited { color: #FF5C1F; } span.table-header { font-size: 120%; font-weight: bold; } th.group-header { background: #185360; color: #fff; text-align: left; font-style: italic; font-size: 115%; border: 1px solid #608090; } /* Summary Tables (functions, variables, etc) * - Each object is described by a single row of the table with * two cells. The left cell gives the object's type, and is * marked with 'code.summary-type'. The right cell gives the * object's name and a summary description. * - CSS styles for the table's header and group headers are * defined above, under 'Table Headers' */ table.summary { border-collapse: collapse; background: #e8f0f8; color: #000000; border: 1px solid #608090; margin-bottom: 0.5em; } td.summary { border: 1px solid #608090; } code.summary-type { font-size: 85%; } table.summary a:link { color: #FF5C1F; } table.summary a:visited { color: #FF5C1F; } /* Details Tables (functions, variables, etc) * - Each object is described in its own div. * - A single-row summary table w/ table-header is used as * a header for each details section (CSS style for table-header * is defined above, under 'Table Headers'). */ table.details { border-collapse: collapse; background: #e8f0f8; color: #585858; border: 1px solid #608090; margin: .2em 0 0 0; } table.details table { color: #fff; } table.details a:link { color: #FF5C1F; } table.details a:visited { color: #FF5C1F; } /* Fields */ dl.fields { margin-left: 2em; margin-top: 1em; margin-bottom: 1em; } dl.fields dd ul { margin-left: 0em; padding-left: 0em; } div.fields { margin-left: 2em; } div.fields p { margin-bottom: 0.5em; } /* Index tables (identifier index, term index, etc) * - link-index is used for indices containing lists of links * (namely, the identifier index & term index). * - index-where is used in link indices for the text indicating * the container/source for each link. * - metadata-index is used for indices containing metadata * extracted from fields (namely, the bug index & todo index). */ table.link-index { border-collapse: collapse; background: #e8f0f8; color: #000000; border: 1px solid #608090; } td.link-index { border-width: 0px; } table.link-index a:link { color: #FF5C1F; } table.link-index a:visited { color: #FF5C1F; } span.index-where { font-size: 70%; } table.metadata-index { border-collapse: collapse; background: #e8f0f8; color: #000000; border: 1px solid #608090; margin: .2em 0 0 0; } td.metadata-index { border-width: 1px; border-style: solid; } table.metadata-index a:link { color: #FF5C1F; } table.metadata-index a:visited { color: #FF5C1F; } /* Function signatures * - sig* is used for the signature in the details section. * - .summary-sig* is used for the signature in the summary * table, and when listing property accessor functions. .sig-name { color: #006080; } .sig-arg { color: #008060; } .sig-default { color: #602000; } .summary-sig { font-family: monospace; } .summary-sig-name { color: #006080; font-weight: bold; } table.summary a.summary-sig-name:link { color: #006080; font-weight: bold; } table.summary a.summary-sig-name:visited { color: #006080; font-weight: bold; } .summary-sig-arg { color: #006040; } .summary-sig-default { color: #501800; } * */ .sig-name { color: #FF5C1F; } .sig-arg { color: #008060; } .sig-default { color: #602000; } .summary-sig { font-family: monospace; } .summary-sig-name { color: #FF5C1F; font-weight: bold; } table.summary a.summary-sig-name:link { color: #FF5C1F; font-weight: bold; } table.summary a.summary-sig-name:visited { color: #FF5C1F; font-weight: bold; } .summary-sig-arg { color: #006040; } .summary-sig-default { color: #FF5C1F; } /* To render variables, classes etc. like functions */ table.summary .summary-name { color: #FF5C1F; font-weight: bold; font-family: monospace; } table.summary a.summary-name:link { color: #FF5C1F; font-weight: bold; font-family: monospace; } table.summary a.summary-name:visited { color: #FF5C1F; font-weight: bold; font-family: monospace; } /* Variable values * - In the 'variable details' sections, each variable's value is * listed in a 'pre.variable' box. The width of this box is * restricted to 80 chars; if the value's repr is longer than * this it will be wrapped, using a backslash marked with * class 'variable-linewrap'. If the value's repr is longer * than 3 lines, the rest will be elided; and an ellipsis * marker ('...' marked with 'variable-ellipsis') will be used. * - If the value is a string, its quote marks will be marked * with 'variable-quote'. * - If the variable is a regexp, it is syntax-highlighted using * the re* CSS classes. */ pre.variable { padding: .5em; margin: 0; background: #dce4ec; color: #000000; border: 1px solid #708890; } .variable-linewrap { color: #604000; font-weight: bold; } .variable-ellipsis { color: #604000; font-weight: bold; } .variable-quote { color: #604000; font-weight: bold; } .variable-group { color: #008000; font-weight: bold; } .variable-op { color: #604000; font-weight: bold; } .variable-string { color: #006030; } .variable-unknown { color: #a00000; font-weight: bold; } .re { color: #000000; } .re-char { color: #006030; } .re-op { color: #600000; } .re-group { color: #003060; } .re-ref { color: #404040; } /* Base tree * - Used by class pages to display the base class hierarchy. */ pre.base-tree { font-size: 80%; margin: 0; } /* Frames-based table of contents headers * - Consists of two frames: one for selecting modules; and * the other listing the contents of the selected module. * - h1.toc is used for each frame's heading * - h2.toc is used for subheadings within each frame. */ h1.toc { text-align: center; font-size: 105%; margin: 0; font-weight: bold; padding: 0; } h2.toc { font-size: 100%; font-weight: bold; margin: 0.5em 0 0 -0.3em; } /* Syntax Highlighting for Source Code * - doctest examples are displayed in a 'pre.py-doctest' block. * If the example is in a details table entry, then it will use * the colors specified by the 'table pre.py-doctest' line. * - Source code listings are displayed in a 'pre.py-src' block. * Each line is marked with 'span.py-line' (used to draw a line * down the left margin, separating the code from the line * numbers). Line numbers are displayed with 'span.py-lineno'. * The expand/collapse block toggle button is displayed with * 'a.py-toggle' (Note: the CSS style for 'a.py-toggle' should not * modify the font size of the text.) * - If a source code page is opened with an anchor, then the * corresponding code block will be highlighted. The code * block's header is highlighted with 'py-highlight-hdr'; and * the code block's body is highlighted with 'py-highlight'. * - The remaining py-* classes are used to perform syntax * highlighting (py-string for string literals, py-name for names, * etc.) pre.py-doctest { padding: .5em; margin: 1em; background: #e8f0f8; color: #000000; border: 1px solid #708890; } table pre.py-doctest { background: #dce4ec; color: #000000; } pre.py-src { border: 2px solid #000000; background: #f0f0f0; color: #000000; } .py-line { border-left: 2px solid #000000; margin-left: .2em; padding-left: .4em; } .py-lineno { font-style: italic; font-size: 90%; padding-left: .5em; } a.py-toggle { text-decoration: none; } div.py-highlight-hdr { border-top: 2px solid #000000; border-bottom: 2px solid #000000; background: #d8e8e8; } div.py-highlight { border-bottom: 2px solid #000000; background: #d0e0e0; } .py-prompt { color: #005050; font-weight: bold;} .py-more { color: #005050; font-weight: bold;} .py-string { color: #006030; } .py-comment { color: #003060; } .py-keyword { color: #600000; } .py-output { color: #404040; } .py-name { color: #000050; } .py-name:link { color: #000050 !important; } .py-name:visited { color: #000050 !important; } .py-number { color: #005000; } .py-defname { color: #000060; font-weight: bold; } .py-def-name { color: #000060; font-weight: bold; } .py-base-class { color: #000060; } .py-param { color: #000060; } .py-docstring { color: #006030; } .py-decorator { color: #804020; } */ /* Use this if you don't want links to names underlined: */ /*a.py-name { text-decoration: none; }*/ pre.py-doctest { padding: .5em; margin: 1em; background: #e8f0f8; color: #000000; border: 1px solid #708890; } table pre.py-doctest { background: #dce4ec; color: #000000; } pre.py-src { border: 2px solid #000000; background: #f0f0f0; color: #000000; } .py-line { border-left: 2px solid #000000; margin-left: .2em; padding-left: .4em; } .py-lineno { font-style: italic; font-size: 90%; padding-left: .5em; } a.py-toggle { text-decoration: none; } div.py-highlight-hdr { border-top: 2px solid #000000; border-bottom: 2px solid #000000; background: #d8e8e8; } div.py-highlight { border-bottom: 2px solid #000000; background: #d0e0e0; } .py-prompt { color: #005050; font-weight: bold;} .py-more { color: #005050; font-weight: bold;} .py-string { color: green; } .py-comment { color: green; } .py-keyword { color: blue; } .py-output { color: #404040; } .py-name { color: #585858;} .py-name:link { color: #FF5C1F !important; } .py-name:visited { color: #FF5C1F !important; } .py-number { color: #005000; } .py-defname { color: #FF5C1F; font-weight: bold; } .py-def-name { color: #FF5C1F; font-weight: bold; } .py-base-class { color: #FF5C1F; } .py-param { color: #000060; } .py-docstring { color: green; } .py-decorator { color: #804020; } /* Graphs & Diagrams * - These CSS styles are used for graphs & diagrams generated using * Graphviz dot. 'img.graph-without-title' is used for bare * diagrams (to remove the border created by making the image * clickable). */ img.graph-without-title { border: none; } img.graph-with-title { border: 1px solid #000000; } span.graph-title { font-weight: bold; } span.graph-caption { } /* General-purpose classes * - 'p.indent-wrapped-lines' defines a paragraph whose first line * is not indented, but whose subsequent lines are. * - The 'nomargin-top' class is used to remove the top margin (e.g. * from lists). The 'nomargin' class is used to remove both the * top and bottom margin (but not the left or right margin -- * for lists, that would cause the bullets to disappear.) */ p.indent-wrapped-lines { padding: 0 0 0 7em; text-indent: -7em; margin: 0; } .nomargin-top { margin-top: 0; } .nomargin { margin-top: 0; margin-bottom: 0; } /* HTML Log */ div.log-block { padding: 0; margin: .5em 0 .5em 0; background: #e8f0f8; color: #000000; border: 1px solid #000000; } div.log-error { padding: .1em .3em .1em .3em; margin: 4px; background: #ffb0b0; color: #000000; border: 1px solid #000000; } div.log-warning { padding: .1em .3em .1em .3em; margin: 4px; background: #ffffb0; color: #000000; border: 1px solid #000000; } div.log-info { padding: .1em .3em .1em .3em; margin: 4px; background: #b0ffb0; color: #000000; border: 1px solid #000000; } h2.log-hdr { background: #70b0ff; color: #000000; margin: 0; padding: 0em 0.5em 0em 0.5em; border-bottom: 1px solid #000000; font-size: 110%; } p.log { font-weight: bold; margin: .5em 0 .5em 0; } tr.opt-changed { color: #000000; font-weight: bold; } tr.opt-default { color: #606060; } pre.log { margin: 0; padding: 0; padding-left: 1em; }
11ghenrylv-mongotest
epydoc.css
CSS
lgpl
20,993
/** * @file EclairMotionEvent.java * @brief * * Copyright (C)2010-2012 Magnus Uppman <magnus.uppman@gmail.com> * License: GPLv3+ */ package com.linuxfunkar.mousekeysremote; import android.view.MotionEvent; public class EclairMotionEvent extends WrapMotionEvent { protected EclairMotionEvent(MotionEvent event) { super(event); } public final int findPointerIndex(int pointerId) { return event.findPointerIndex(pointerId); } public final int getPointerCount() { return event.getPointerCount(); } public final int getPointerId(int pointerIndex) { return event.getPointerId(pointerIndex); } public final float getX(int pointerIndex) { return event.getX(pointerIndex); } public final float getY(int pointerIndex) { return event.getY(pointerIndex); } }
091420009-dd
src/com/linuxfunkar/mousekeysremote/EclairMotionEvent.java
Java
gpl3
788
package com.linuxfunkar.mousekeysremote; import java.io.UnsupportedEncodingException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.PBEParameterSpec; import android.util.Base64; class Security { private static final String algorithm = "PBEWithMD5AndDES"; private static final byte[] salt = new byte[] { 67, (byte) 222, 18, (byte) 174, 59, (byte) 243, 69, 125 }; private SecretKey key; private Cipher cipher; public Security(String password) throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException, NoSuchPaddingException, InvalidAlgorithmParameterException { SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm); char[] pass = password.toCharArray(); key = factory.generateSecret(new PBEKeySpec(pass)); cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(salt, 2048)); } public String encrypt(String msg) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException { byte[] inputBytes = msg.getBytes("UTF-8"); byte[] encbytes = cipher.doFinal(inputBytes); String ret = Base64.encodeToString(encbytes, Base64.NO_WRAP); return ret; } }
091420009-dd
src/com/linuxfunkar/mousekeysremote/Security.java
Java
gpl3
1,698
/** * @file ColorPickerDialog.java * @brief * * Copyright (C)2012 Magnus Uppman <magnus.uppman@gmail.com> * License: GPLv3+ */ package com.linuxfunkar.mousekeysremote; import android.app.Dialog; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorMatrix; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.SweepGradient; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; public class ColorPickerDialog extends Dialog { public static final String PROP_INITIAL_COLOR = "InitialColor"; public static final String PROP_PARENT_WIDTH = "Width"; public static final String PROP_PARENT_HEIGHT = "Height"; public static final String PROP_COLORELEM = "ColorElement"; private int measuredWidth; private int measuredHeight; public interface OnColorChangedListener { void colorChanged(int color, int elem); } protected OnColorChangedListener colorChangedListener; private int mInitialColor; private int colorElem; private class ColorPickerView extends View { private Paint mPaint; private Paint mCenterPaint; private final int[] mColors; private OnColorChangedListener mListener; ColorPickerView(Context context, int color) { super(context); mColors = new int[] { 0xFFFF0000, 0xFFFF00FF, 0xFF0000FF, 0xFF00FFFF, 0xFF88FF88, 0xFFFFFF00, 0xFFFF0000, 0xFF000000, 0xFF888888, 0xFF00FF00, 0xFFFF0000 // 0xFF000000, 0xFF0000FF, 0xFFFFFFFF, 0xFF00FF00, 0xFF000000, // 0xFFFF0000, 0xFFFFFFFF, 0xFFFFFF00, 0xFF000000, 0xFFFFFFFF, // 0xFF00FFFF, 0xFF000000 }; // 0xFFFFFFFF, 0xFF000000 Shader s = new SweepGradient(0, 0, mColors, null); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setShader(s); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeWidth(32); mCenterPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mCenterPaint.setColor(color); mCenterPaint.setStrokeWidth(5); } private boolean mTrackingCenter; private boolean mHighlightCenter; private void setOnColorChangedListener(OnColorChangedListener listener) { mListener = listener; } @Override protected void onDraw(Canvas canvas) { float r = CENTER_X - mPaint.getStrokeWidth() * 0.5f; canvas.translate(CENTER_X, CENTER_X); canvas.drawOval(new RectF(-r, -r, r, r), mPaint); canvas.drawCircle(0, 0, CENTER_RADIUS, mCenterPaint); if (mTrackingCenter) { int c = mCenterPaint.getColor(); mCenterPaint.setStyle(Paint.Style.STROKE); if (mHighlightCenter) { mCenterPaint.setAlpha(0xFF); } else { mCenterPaint.setAlpha(0x80); } canvas.drawCircle(0, 0, CENTER_RADIUS + mCenterPaint.getStrokeWidth(), mCenterPaint); mCenterPaint.setStyle(Paint.Style.FILL); mCenterPaint.setColor(c); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int measuredHeight = MeasureSpec.getSize(heightMeasureSpec); int measuredWidth = MeasureSpec.getSize(widthMeasureSpec); MouseKeysRemote.debug("x: " + measuredWidth + "y: " + measuredHeight); // setMeasuredDimension(widthMeasureSpec / 2, heightMeasureSpec /2); setMeasuredDimension(CENTER_X * 2, CENTER_Y * 2); } private int CENTER_X = measuredWidth / 3; // 100; private int CENTER_Y = measuredWidth / 3; private int CENTER_RADIUS = measuredWidth / 6; private int floatToByte(float x) { int n = java.lang.Math.round(x); return n; } private int pinToByte(int n) { if (n < 0) { n = 0; } else if (n > 255) { n = 255; } return n; } private int ave(int s, int d, float p) { return s + java.lang.Math.round(p * (d - s)); } private int interpColor(int colors[], float unit) { if (unit <= 0) { return colors[0]; } if (unit >= 1) { return colors[colors.length - 1]; } float p = unit * (colors.length - 1); int i = (int) p; p -= i; // now p is just the fractional part [0...1) and i is the index int c0 = colors[i]; int c1 = colors[i + 1]; int a = ave(Color.alpha(c0), Color.alpha(c1), p); int r = ave(Color.red(c0), Color.red(c1), p); int g = ave(Color.green(c0), Color.green(c1), p); int b = ave(Color.blue(c0), Color.blue(c1), p); return Color.argb(a, r, g, b); } private int rotateColor(int color, float rad) { float deg = rad * 180 / 3.1415927f; int r = Color.red(color); int g = Color.green(color); int b = Color.blue(color); ColorMatrix cm = new ColorMatrix(); ColorMatrix tmp = new ColorMatrix(); cm.setRGB2YUV(); tmp.setRotate(0, deg); cm.postConcat(tmp); tmp.setYUV2RGB(); cm.postConcat(tmp); final float[] a = cm.getArray(); int ir = floatToByte(a[0] * r + a[1] * g + a[2] * b); int ig = floatToByte(a[5] * r + a[6] * g + a[7] * b); int ib = floatToByte(a[10] * r + a[11] * g + a[12] * b); return Color.argb(Color.alpha(color), pinToByte(ir), pinToByte(ig), pinToByte(ib)); } private static final float PI = 3.1415926f; @Override public boolean onTouchEvent(MotionEvent event) { float x = event.getX() - CENTER_X; float y = event.getY() - CENTER_Y; boolean inCenter = java.lang.Math.sqrt(x * x + y * y) <= CENTER_RADIUS; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mTrackingCenter = inCenter; if (inCenter) { mHighlightCenter = true; invalidate(); break; } case MotionEvent.ACTION_MOVE: if (mTrackingCenter) { if (mHighlightCenter != inCenter) { mHighlightCenter = inCenter; invalidate(); } } else { float angle = (float) java.lang.Math.atan2(y, x); // need to turn angle [-PI ... PI] into unit [0....1] float unit = angle / (2 * PI); if (unit < 0) { unit += 1; } mCenterPaint.setColor(interpColor(mColors, unit)); invalidate(); } break; case MotionEvent.ACTION_UP: if (mTrackingCenter) { if (inCenter) { mListener.colorChanged(mCenterPaint.getColor(), colorElem); } mTrackingCenter = false; // so we draw w/o halo invalidate(); } break; } return true; } } public ColorPickerDialog(Context context, Bundle props) { super(context); mInitialColor = props.getInt(PROP_INITIAL_COLOR, 0); measuredWidth = props.getInt(PROP_PARENT_WIDTH, 640); measuredHeight = props.getInt(PROP_PARENT_HEIGHT, 480); colorElem = props.getInt(PROP_COLORELEM, 0); } public void setColorChangedListener(OnColorChangedListener listener) { colorChangedListener = listener; } protected void fireColorChangedListener(int color, int colorElem) { colorChangedListener.colorChanged(color, colorElem); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); OnColorChangedListener l = new OnColorChangedListener() { public void colorChanged(int color, int colorElem) { fireColorChangedListener(color, colorElem); dismiss(); } }; ColorPickerView colorPickerView = new ColorPickerView(getContext(), mInitialColor); colorPickerView.setOnColorChangedListener(l); setContentView(colorPickerView); setTitle("Pick a Color"); } }
091420009-dd
src/com/linuxfunkar/mousekeysremote/ColorPickerDialog.java
Java
gpl3
7,272
/** * @file CustomDrawableView.java * @brief * * Copyright (C)2010-2012 Magnus Uppman <magnus.uppman@gmail.com> * License: GPLv3+ */ package com.linuxfunkar.mousekeysremote; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.RectShape; import android.view.View; import com.linuxfunkar.mousekeysremote.MouseKeysRemote.EditMode; public class CustomDrawableView extends View { private static final String MARK_S = "(s)"; private static final String MARK_C = "(C)"; private static final String MARK_HASH = "(#)"; private static final String MARK_STAR = "(*)"; private ShapeDrawable mDrawable, backGround, wheel; private int measuredHeight = 0; private int measuredWidth = 0; private int keyWidth = 0; private int keyHeight = 0; private RectF keyRect; private Paint rectPaint, textPaint, textLayoutPaint, textLabelLayoutPaint; // Convert the dps to pixels final float scale = getContext().getResources().getDisplayMetrics().density; final float xdpi = getContext().getResources().getDisplayMetrics().xdpi; float tsize, t_layout_size, l_layout_size; private String mark; private EditMode mode = EditMode.None; public CustomDrawableView(Context context) { super(context); // private int a = (RemotePC.) // colorObj = new Color(); keyRect = new RectF(); rectPaint = new Paint(); textPaint = new Paint(); textLayoutPaint = new Paint(); textLabelLayoutPaint = new Paint(); rectPaint.setStyle(Paint.Style.FILL_AND_STROKE); textPaint.setStyle(Paint.Style.FILL_AND_STROKE); // textPaint.setFakeBoldText(true); textLabelLayoutPaint.setAntiAlias(true); textPaint.setAntiAlias(true); textPaint.setTextAlign(Paint.Align.CENTER); // rectPaint.setColor(R.color.key_color); // rectPaint.setColor(0xff74AC23); // rectPaint.setColor(0xff333333); textPaint.setColor(0xffffffff); // textPaint.setColor(0xff333333); // textPaint.setStrokeWidth(1); // textPaint.set tsize = textPaint.getFontSpacing(); textLayoutPaint.setColor(0xffffffff); // Layout number textLabelLayoutPaint.setColor(0xaa00ff00); // Layout label mDrawable = new ShapeDrawable(new RectShape()); // Mousepad // mDrawable.getPaint().setColor(0xff000088); // Blue mDrawable.getPaint().setColor(0xff2222ff); // Blue wheel = new ShapeDrawable(new RectShape()); // Mousepad wheel // wheel.getPaint().setColor(0xff555588); // wheel.getPaint().setColor(0xff8888ff); // backGround = new ShapeDrawable(new RectShape()); // Keys background // backGround.getPaint().setColor(0xff8888ff); // Blue backGround.getPaint().setColor(0xff000000); // Black MouseKeysRemote.mouseWheelWidth = (int) (xdpi / 2); } public void setMark(EditMode mode) { this.mode = mode; if (mode == EditMode.Binding) { mark = MARK_STAR; } else if (mode == EditMode.Name) { mark = MARK_HASH; } else if (mode == EditMode.Color) { mark = MARK_C; } else if (mode == EditMode.Sticky) { mark = MARK_S; this.mode = EditMode.None; } else { mark = ""; } } @Override protected void onMeasure(int wMeasureSpec, int hMeasureSpec) { measuredHeight = MeasureSpec.getSize(hMeasureSpec); measuredWidth = MeasureSpec.getSize(wMeasureSpec); /* * if (RemotePC2.enableMouseWheel) // Fill entire right hand side. Maybe * later.. { RemotePC2.xOffsetRight = (int)(xdpi/2); } else * RemotePC2.xOffsetRight = 0; */ if (MouseKeysRemote.enableMousePad) { float calc = (float) measuredHeight * (((float) MouseKeysRemote.mousepadRelativeSize / 100)); // RemotePC2.debug ((int)calc); MouseKeysRemote.yOffsetBottom = (int) calc; // 200; //measuredHeight // - // measuredHeight/(RemotePC2.mousepadRelativeSize/10); // // Size of // keypad/mousepad } else MouseKeysRemote.yOffsetBottom = 0; try { keyWidth = ((measuredWidth - MouseKeysRemote.xOffsetRight) - MouseKeysRemote.xOffsetLeft) / MouseKeysRemote.numberOfKeyCols; keyHeight = ((measuredHeight - MouseKeysRemote.yOffsetBottom) - MouseKeysRemote.yOffsetTop) / MouseKeysRemote.numberOfKeyRows; } catch (Exception e) { MouseKeysRemote.debug(e.toString()); } // RemotePC2.debug("measuredHeight: " + measuredHeight + // " measuredWidth: " + measuredWidth); // RemotePC2.debug("keyWidth: " + keyWidth + "keyHeight: " + keyHeight); // textLayoutPaint.setTextSize(measuredHeight); textLabelLayoutPaint.setTextSize(measuredHeight / 16); // t_layout_size = textLayoutPaint.getFontSpacing(); l_layout_size = textLabelLayoutPaint.getFontSpacing(); // RemotePC2.debug("t_layout_size: " + t_layout_size); // textPaint.setTextSize(keyHeight/6); MouseKeysRemote.keyWidth = keyWidth; MouseKeysRemote.keyHeight = keyHeight; setMeasuredDimension(measuredWidth, measuredHeight); } protected void onDraw(Canvas canvas) { // RemotePC.debug("onDraw: h:" + getMeasuredHeight() +" w: " + // getMeasuredWidth()); backGround.getPaint().setColor(MouseKeysRemote.backCol); backGround.setBounds(0, 0, measuredWidth, measuredHeight); backGround.draw(canvas); textPaint.setTextScaleX(MouseKeysRemote.textSize); if (MouseKeysRemote.calibrate == true) { canvas.drawText("Calibrate sensors", 0, measuredHeight / 4, textLabelLayoutPaint); canvas.drawText("Touch when ready!", 0, measuredHeight / 2, textLabelLayoutPaint); } else { drawMousepad(canvas); drawKeys(canvas); drawLayoutlabel(canvas); } } private void drawLayoutlabel(Canvas canvas) { // Draw layout label String layoutLabel = MouseKeysRemote.keys_layout_name; float layoutLabelWidth = textLabelLayoutPaint.measureText(layoutLabel); canvas.drawText(layoutLabel, (measuredWidth / 2) - layoutLabelWidth / 2, measuredHeight - (l_layout_size / 2), textLabelLayoutPaint); } private void drawKeys(Canvas canvas) { int keyCnt = 0; int keyCol; for (int i = 0; i < MouseKeysRemote.numberOfKeyRows; i++) { // yCnt = yCnt + (keyHeight * i); // Row for (int j = 0; j < MouseKeysRemote.numberOfKeyCols; j++) { MouseKeysRemote.x1Pos[keyCnt] = MouseKeysRemote.xOffsetLeft + (keyWidth * j); MouseKeysRemote.y1Pos[keyCnt] = MouseKeysRemote.yOffsetTop + (keyHeight * i); MouseKeysRemote.x2Pos[keyCnt] = MouseKeysRemote.xOffsetLeft + (keyWidth * j) + keyWidth; MouseKeysRemote.y2Pos[keyCnt] = MouseKeysRemote.yOffsetTop + (keyHeight * i) + keyHeight; // RemotePC2.debug("keyRect.toString: " + // keyRect.toString()); int sticky = 0; // MouseKeysRemote.getKeyValueSticky(keyCnt + // 1); keyCol = MouseKeysRemote.mySharedPreferences.getInt("KeyColor" + "layout" + MouseKeysRemote.keys_layout + "key" + (keyCnt + 1), 0xff2222bb); // // int r = Color.red(keyCol); // int g = Color.green(keyCol); // int b = Color.blue(keyCol); // newCol = Color.argb(255, (255 -r)*2 & 0xFF, (255 -g)*2 & // 0xFF ,(255 -b)*2 & 0xFF); // if ((MouseKeysRemote.keyState[keyCnt] == MouseKeysRemote.KEY_STATE_UP || (MouseKeysRemote .getKeyValue(keyCnt + 1) == Constants.DUMMY && mode == EditMode.None)) && sticky == MouseKeysRemote.UNSTUCK_KEY) // Button // up { rectPaint.setStyle(Paint.Style.FILL_AND_STROKE); rectPaint.setColor(keyCol); keyRect.set( MouseKeysRemote.x1Pos[keyCnt] + (keyWidth / 10), MouseKeysRemote.y1Pos[keyCnt] + (keyHeight / 10), MouseKeysRemote.x2Pos[keyCnt] - (keyWidth / 10), MouseKeysRemote.y2Pos[keyCnt] - (keyHeight / 10)); canvas.drawRoundRect(keyRect, (float) keyWidth / 4, (float) keyHeight / 4, rectPaint); rectPaint.setStyle(Paint.Style.STROKE); // rectPaint.setColor(newCol); rectPaint.setColor(0xffffffff); // Outer keyRect.set( MouseKeysRemote.x1Pos[keyCnt] + (keyWidth / 10), MouseKeysRemote.y1Pos[keyCnt] + (keyHeight / 10), MouseKeysRemote.x2Pos[keyCnt] - (keyWidth / 10), MouseKeysRemote.y2Pos[keyCnt] - (keyHeight / 10)); canvas.drawRoundRect(keyRect, (float) keyWidth / 4, (float) keyHeight / 4, rectPaint); } else // Down { rectPaint.setStyle(Paint.Style.FILL_AND_STROKE); rectPaint.setColor(0xff999999); // Key down keyRect.set( MouseKeysRemote.x1Pos[keyCnt] + (keyWidth / 10), MouseKeysRemote.y1Pos[keyCnt] + (keyHeight / 10), MouseKeysRemote.x2Pos[keyCnt] - (keyWidth / 10) - (keyWidth / 10) / 2, MouseKeysRemote.y2Pos[keyCnt] - (keyHeight / 10) - (keyHeight / 10) / 2); canvas.drawRoundRect(keyRect, (float) keyWidth / 4, (float) keyHeight / 4, rectPaint); } if (MouseKeysRemote.getKeyValue(keyCnt + 1) == Constants.DUMMY && mode == EditMode.None) { } else { String keyName; if (mode == EditMode.Binding) { keyName = mark + Constants.getActionName(MouseKeysRemote .getKeyValue(keyCnt + 1)); } else { keyName = mark + MouseKeysRemote.mySharedPreferences .getString( "nameOfKey" + "layout" + MouseKeysRemote.keys_layout + "key" + (keyCnt + 1), Constants .getActionName(MouseKeysRemote .getKeyValue(keyCnt + 1))); } // MouseKeysRemote.debug("nameOfKey" + "layout" + // MouseKeysRemote.keys_layout + "key" + (keyCnt + 1)); // float keyNameWidth = // backGround.getPaint().measureText(keyName); // RemotePC2.debug("tsize: " + tsize); // canvas.drawText (keyName, // MouseKeysRemote.x1Pos[keyCnt] + (keyWidth/2) - // (keyNameWidth/2), MouseKeysRemote.y1Pos[keyCnt]+ // keyHeight/2 + (int)tsize/2, textPaint); // canvas.drawText (keyName, // MouseKeysRemote.x1Pos[keyCnt] + (keyWidth/10) + 2, // MouseKeysRemote.y1Pos[keyCnt]+ keyHeight/2 + // (int)tsize/2, textPaint); textPaint.setColor(MouseKeysRemote.textCol); canvas.drawText(keyName, MouseKeysRemote.x1Pos[keyCnt] + (keyWidth / 2), MouseKeysRemote.y1Pos[keyCnt] + keyHeight / 2 + (int) tsize / 2, textPaint); } keyCnt++; } } } private void drawMousepad(Canvas canvas) { // Draw mouse pad if (MouseKeysRemote.enableMousePad) { // Mousepad background mDrawable.getPaint().setColor(MouseKeysRemote.mousepadCol); mDrawable.setBounds(0, (measuredHeight - MouseKeysRemote.yOffsetBottom), measuredWidth, measuredHeight); mDrawable.draw(canvas); // RemotePC2.debug("scale: " + scale+ "xdpi: " + xdpi); // Mousewheel background if (MouseKeysRemote.enableMouseWheel) { // wheel.setBounds(measuredWidth - // (int)(xdpi/2),(RemotePC2.yOffsetTop), measuredWidth , // measuredHeight); wheel.getPaint().setColor(MouseKeysRemote.mousewheelCol); wheel.setBounds( measuredWidth - MouseKeysRemote.mouseWheelWidth, (measuredHeight - MouseKeysRemote.yOffsetBottom), measuredWidth, measuredHeight); wheel.draw(canvas); } // canvas.save(); } } }
091420009-dd
src/com/linuxfunkar/mousekeysremote/CustomDrawableView.java
Java
gpl3
11,192
package com.linuxfunkar.mousekeysremote; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.text.Editable; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class SimpleTextDialog extends Dialog { private TextView lbl; private EditText txt; private String oldText = ""; private OnTextChangedListener listener; public SimpleTextDialog(Context context) { super(context); } public void show(String title, String label) { super.show(); setTitle(title); lbl.setText(label); txt.setText(oldText); } public void show(String title, String label, String oldText) { this.oldText = oldText; show(title, label); } public void setOnTextChangedListener(OnTextChangedListener listener) { this.listener = listener; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setCancelable(true); setContentView(R.layout.simple_text_dialog); lbl = (TextView) findViewById(R.id.stdialog_label); txt = (EditText) findViewById(R.id.stdialog_text); txt.addTextChangedListener(new TextWatcherAdapter() { @Override public void afterTextChanged(Editable s) { Button ok = (Button) findViewById(R.id.stdialog_pbOkay); ok.setEnabled(!s.toString().equals(oldText)); } }); Button ok = (Button) findViewById(R.id.stdialog_pbOkay); ok.setEnabled(false); ok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listener.onTextChanged(txt.getText().toString()); dismiss(); } }); Button cancel = (Button) findViewById(R.id.stdialog_pbCancel); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { cancel(); } }); } public interface OnTextChangedListener { void onTextChanged(String text); } }
091420009-dd
src/com/linuxfunkar/mousekeysremote/SimpleTextDialog.java
Java
gpl3
2,011
package com.linuxfunkar.mousekeysremote; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.graphics.LightingColorFilter; import android.util.AttributeSet; import android.view.ContextMenu.ContextMenuInfo; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.TableLayout; import android.widget.TableRow; public class ButtonView extends TableLayout { private SharedPreferences prefs; private int layout = 0; private Button lastButton; private OnKeyListener keyListener; private AdapterView.AdapterContextMenuInfo menuInfo; public ButtonView(Context context) { super(context); } public ButtonView(Context context, AttributeSet attrs) { super(context, attrs); } private void init(Context context) { prefs = context.getSharedPreferences("MY_PREFS", Activity.MODE_PRIVATE); layout = prefs.getInt("layout", 0); int numberOfKeyRows = prefs.getInt("numberOfKeyRows" + layout, 7); int numberOfKeyCols = prefs.getInt("numberOfKeyCols" + layout, 7); createButtons(numberOfKeyRows, numberOfKeyCols); } @Override protected void onFinishInflate() { super.onFinishInflate(); if (!isInEditMode()) init(getContext()); } private void createButtons(int rows, int cols) { this.setWeightSum(rows); for (int i = 0; i < rows; i++) { TableRow row = new TableRow(getContext()); row.setWeightSum(cols); for (int j = 0; j < cols; j++) { Button b = new Button(getContext()); int key_num = i * cols + j + 1; b.setText(Preferences.getInstance(getContext()).getKeyLabel( key_num)); b.setTag(R.id.button_id, "" + key_num); b.setTag(R.id.button_sticky, Boolean.valueOf(Preferences .getInstance(getContext()).isButtonSticky(key_num))); b.setTag(Integer.valueOf(Preferences.getInstance(getContext()) .getKeyValue(key_num))); b.setVisibility((Preferences.getInstance(getContext()) .isButtonVisible(key_num)) ? View.VISIBLE : View.INVISIBLE); int color = Preferences.getInstance(getContext()).getKeyColor( key_num); if (color != -1) b.getBackground().setColorFilter( new LightingColorFilter(color, android.R.color.black)); b.setClickable(false); b.setLongClickable(true); b.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { lastButton = (Button) v; showContextMenuForChild(v); return true; } }); b.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { lastButton = (Button) v; int key_num = Integer.valueOf(lastButton.getTag( R.id.button_id).toString()); boolean sticky = Preferences.getInstance(getContext()) .isButtonSticky(key_num); if (sticky) { if (event.getAction() == MotionEvent.ACTION_UP) { if (event.getEventTime() - event.getDownTime() < 2000) { lastButton.setPressed(!lastButton .isPressed()); if (lastButton.isPressed()) lastButton.setText(Preferences .getInstance(getContext()) .getKeyLabel(key_num) .toUpperCase()); else lastButton.setText(Preferences .getInstance(getContext()) .getKeyLabel(key_num)); } else { showContextMenuForChild(v); return true; } } onTouchEvent(event); return true; } onTouchEvent(event); return false; } }); row.addView(b); b.setLayoutParams(new TableRow.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1)); } addView(row); row.setLayoutParams(new TableLayout.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1)); } } @Override public boolean onTouchEvent(MotionEvent event) { if (lastButton != null) { int keyValue = Integer.valueOf(lastButton.getTag().toString()) .intValue(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: onKeyListener(lastButton, keyValue, new KeyEvent( KeyEvent.ACTION_DOWN, keyValue)); return true; case MotionEvent.ACTION_UP: onKeyListener(lastButton, keyValue, new KeyEvent( KeyEvent.ACTION_UP, keyValue)); return true; } lastButton = null; } return false; } public void unhideAll() { unhideAll(this); } private void unhideAll(ViewGroup root) { int i = 0; View child = root.getChildAt(i++); while (child != null) { if (!(child instanceof ViewGroup)) { child.setVisibility(View.VISIBLE); if (child instanceof Button) { Preferences.getInstance(getContext()).setButtonVisible( Integer.valueOf(child.getTag(R.id.button_id) .toString()), true); } } else unhideAll((ViewGroup) child); child = root.getChildAt(i++); } } @Override public boolean showContextMenuForChild(View originalView) { menuInfo = new AdapterView.AdapterContextMenuInfo(originalView, -1, -1); return super.showContextMenuForChild(originalView); } @Override protected ContextMenuInfo getContextMenuInfo() { return menuInfo; } protected void onKeyListener(View view, int keyValue, KeyEvent event) { if (keyListener != null) keyListener.onKey(view, keyValue, event); } public void setOnKeyListener(OnKeyListener listener) { keyListener = listener; } }
091420009-dd
src/com/linuxfunkar/mousekeysremote/ButtonView.java
Java
gpl3
5,835
/** * @file MouseKeysRemote.java * @brief * * Copyright (C)2010-2012 Magnus Uppman <magnus.uppman@gmail.com> * License: GPLv3+ */ /** * Changelog: * 20101219 v.1.1 * Bugfix. New keys don't have a valid state when changing rows and cols. * Bugfix. Settings screen isn't scrollable. * Added key N/C for the possibility of dummy keys. * 20101229 v.1.2 * Bugfix: Mouse wheel buttons didn't work. * 2011-01-07 v.1.3 * Added mouseclick on tap * "Send text" now always send a CR/LF at the end. * Reduced mousewheel sensitivity * Fixed back button * Added mouse wheel on touchpad * Changed postInvalidate to invalidate in keypad+ * 2011-01-17 v1.4 * Added password * Changed icon * 2011-03-?? * Changed name to MouseKeys.. * 2011-03-29 v1.04 * Removed transparency for buttons. Reverted to black background. * * Changed name to MouseKeysRemote * 2011-05-20 v1.01 * DEFAULT_TOUCH_TIME = 200 * Added sticky keys * * 2011-07-24 v1.03 * Keyboard is now displayed automatically * Layouts can be named. * Increased number of layouts to 16. * * Notes: * Special characters and zoom: * Must enable Compose and Meta key in KDE. * System settings -> Keyboard layout -> Advanced * Free version exactly the same except only one layout. * DEFAULT_TOUCH_TIME = 100 * * 2011-08-17 v1.03.1 * Better sensitivity control to avoid jumping mouse. * 2011-09-02 v1.03.2 * Further improvements to mouse and mousewheel sensitivity control. * Each layout can now be set to portrait, landscape or auto-rotate. * Display can be set to always on per layout. * Wifi is now never disabled when the app is running. * Bugfix where pinch to zoom was wrongly activated when pressing a button after moving the mouse. * Haptic feedback is now configurable per layout. * 2011-09-03 v1.03.3 * Bugfix where tap on touch didn't work on some devices. * 2011-09-11 v1.03.4 * Added support for install to SD-card. * Language setting is now sent to the server on resume. * Added sensor-assisted cursor movement. * 2011-09-13 v1.03.5 * Reduced mouse sensitivity when a finger is lifted to avoid jumping mouse. * 2011-09-24 v1.03.6 * Improved mouse accuracy. * More sensor features. * 2011-09-27 v1.03.7 * Added North, South etc.. keys which maps to the cursor keys. The key North-W maps for example to both cursor up and cursor left. * Reduced the size of the hit-rectangle on keys to better match the actual graphics. * 2011-10-17 v1.03.8 * Added checkbox for enable/disable click on tap. * 2012-01-10 v1.03.9 * Button colors can be changed as a separate edit mode. * Background and text colors can be changed (from settings). * 2012-01-27 v1.03.10 * Fix for password and keyboard bug. Thanks to "Carl" for the bug report! * Increased text size. * 2012-02-20 v.104.1 * Added checkbox for enable/disable pinch zoom. * Increased mouse sensitivity by removing the 25ms deadzone before moving the mouse. * Minor color changes to the color picker. * 2012-10-10 2.0 (Banbury) * Major rewrite. */ package com.linuxfunkar.mousekeysremote; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import yuku.ambilwarna.AmbilWarnaDialog; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.graphics.LightingColorFilter; import android.graphics.Paint; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.net.wifi.WifiManager; import android.net.wifi.WifiManager.WifiLock; import android.os.Bundle; import android.os.IBinder; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Display; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.ScaleGestureDetector.SimpleOnScaleGestureListener; import android.view.Surface; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RadioButton; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; public class MouseKeysRemote extends Activity implements ColorPickerDialog.OnColorChangedListener, OnClickListener, OnItemClickListener, OnItemSelectedListener, SensorEventListener { private static final String TAG = "MouseKeysRemote"; private static final boolean debug = false; // private static final boolean debug=true; private SensorManager mSensorManager; private PowerManager mPowerManager; private WindowManager mWindowManager; private Display mDisplay; private WakeLock mWakeLock; private Sensor mAccelerometer; private WifiManager mWifiManager; public static final int KEYPAD_STATE_COMPAT = 0; public static final int KEYPAD_STATE_TOUCH = 1; public static final int KEY_STATE_DOWN = 0; public static final int KEY_STATE_UP = 1; public static final int KEY_STATE_DOWN_PENDING_UP = 2; public static final int KEY_STATE_DOWN_PENDING_CONFIRMED_DOWN = 3; public static final int MOUSE_NO_GESTURE = 0; public static final int MOUSE_AWAITING_GESTURE = 1; public static final int MOUSE_ZOOM = 2; private static final int MENU_QUIT = 1; private static final int MENU_MORE = 2; private static final int MENU_LAYOUT = 3; private static final int MENU_MAIN = 4; private static final int MENU_EDIT = 5; private static final int MENU_KP_TOUCH = 6; private static final int MENU_STICK = 7; private static final int MENU_UNSTICK = 8; private static final int MENU_ABOUT = 9; private static final int MENU_CALIBRATE = 10; private static final int MENU_COLOR = 11; private static final int MENU_UNHIDE = 12; private enum ColorElement { Text(0), Back(1), MousePad(2), MouseWheel(3), Button(4); private final int value; private ColorElement(int value) { this.value = value; } public int toInt() { return value; } } private static final int SENSORS_MOUSE = 0; private static final int SENSORS_CURSOR = 1; private static final int SENSORS_MOUSE_GAME = 2; private static final int MAX_KEYS = 200; private static final int DEFAULT_NUM_ROWS = 5; private static final int DEFAULT_NUM_COLS = 4; private static final int DEFAULT_MP_SIZE = 50; private static final int DEFAULT_LAYOUTS = 32; private static final int DEFAULT_MOUSE_ACC = 2; private static final float DEFAULT_TEXT_SIZE = 1.2f; private static final int DEFAULT_LANGUAGE = 1; // English (0 = Custom, for // more languages update // lang_array in // strings.xml) public static final int STUCK_KEY = 0; public static final int UNSTUCK_KEY = 1; public static final int UNSTUCK_KEY_PENDING_RELEASE = 2; // public static final int NO_EDIT = 0; // public static final int KEY_BINDING_EDIT = 1; // public static final int KEY_NAME_EDIT = 2; // public static final int KEY_COL_EDIT = 3; public enum EditMode { None, Binding, Name, Color, Sticky } public static final int DEFAULT_SENSOR_DELAY = SensorManager.SENSOR_DELAY_FASTEST; // public static final int DEFAULT_SENSOR_DELAY = // SensorManager.SENSOR_DELAY_GAME; // public static final int DEFAULT_SENSOR_DELAY = // SensorManager.SENSOR_DELAY_NORMAL; public static final float DEFAULT_SENSOR_SENSITIVTY = 1f; private EditMode edit = EditMode.None; private boolean sticky = false; public String passwd; // = new String(""); public String host; static public int lang_pos; static public int mouse_speed_pos; static public int layout_mode_pos; static public boolean calibrate = false; static public int keys_layout; static public int key_to_edit; TextView heading; EditText ip; Button send; Spinner spinner; Spinner mouse_spinner; Spinner layout_mode_spinner; private LinearLayout layout_action; private ListView choose_action; private EditText edCmd; TextView action_text; LinearLayout layout_select; ListView choose_layout; TextView layout_text; EditText key_name; float mLastTouchX = -1; float mLastTouchY = -1; float mPosX = -1; float mPosY = -1; int accX = -1; float accXFloat = -1; float xPosLast; int accY = -1; float accYFloat = -1; float yPosLast; float mouseMovePressure; float currentMousePressure; long down; long up; long last_up = 0; int action; int xPos = -1; int yPos = -1; float xPosFloat = -1; float yPosFloat = -1; int pointerIndex = -1; int pointerCnt = 1; float calibrate_x = 0; float calibrate_y = 0; CustomDrawableView keyPadView; static public int[] keyState; // key current state (up/down) static public int[] x1Pos; static public int[] y1Pos; static public int[] x2Pos; static public int[] y2Pos; static public int numberOfKeyRows = DEFAULT_NUM_ROWS; static public int numberOfKeyCols = DEFAULT_NUM_COLS; static public int mousepadRelativeSize = DEFAULT_MP_SIZE; static public float textSize = DEFAULT_TEXT_SIZE; static public int xOffsetLeft = 0; static public int xOffsetRight = 0; static public int yOffsetTop = 0; static public int yOffsetBottom = 0; // Will be automatically calculated static int[] key_actions; // Available actions static int number_of_keycodes; // Number of currently defined key bindings public String[] EDIT_Names; // Keys public String[] LAYOUT_Names = { // Layouts "Layout 1", "Layout 2", "Layout 3", "Layout 4", "Layout 5", "Layout 6", "Layout 7", "Layout 8", "Layout 9", "Layout 10", "Layout 11", "Layout 12", "Layout 13", "Layout 14", "Layout 15", "Layout 16" }; public String[] LAYOUT_Names3 = new String[DEFAULT_LAYOUTS]; static public boolean enableMouseWheel; public static int mouseWheelWidth = 0; static public boolean enableVibrate; static public boolean enableMousePad; static public boolean enableAlwaysOn; static public boolean enableSensors; static public boolean enableSensorsX; static public boolean enableSensorsY; static public boolean enableClickOnTap; static public boolean enablePinchZoom; static public WrapMotionEvent ev; NotificationManager nm; Notification vibrateNotification; static public SharedPreferences mySharedPreferences; static public String keys_layout_name; private int sensors_mode; float oldDist = 1f; int port; int old_zoom; float xPosFirstFloat; float yPosFirstFloat; float accXFloatOld; float accYFloatOld; float accXFloatDiff; float accYFloatDiff; int mouseMovePointer; float sensorRotateLeft = DEFAULT_SENSOR_SENSITIVTY; float sensorRotateRight = -DEFAULT_SENSOR_SENSITIVTY; float sensorRotateForward = DEFAULT_SENSOR_SENSITIVTY; float sensorRotateBack = -DEFAULT_SENSOR_SENSITIVTY; // float sensorOffsetZ = 4f; float sensorOffsetY = 0f; float sensorHysteris = 0.2f; public static final int ROTATE_X_NONE = 0; public static final int ROTATE_X_LEFT = 1; public static final int ROTATE_X_RIGHT = 2; public static final int ROTATE_Z_NONE = 0; public static final int ROTATE_Z_FORWARD = 1; public static final int ROTATE_Z_BACK = 2; public static final int ROTATE_Y_NONE = 0; public static final int ROTATE_Y_FORWARD = 1; public static final int ROTATE_Y_BACK = 2; int sensorStateX = ROTATE_X_NONE; int sensorStateZ = ROTATE_Z_NONE; int sensorStateY = ROTATE_Y_NONE; float mSensorX = 0; float mSensorY = 0; float mSensorZ = 0; PowerManager.WakeLock wl; private WifiLock wifiLock = null; static public int keyWidth = 0; static public int keyHeight = 0; private View mousePanel; private GestureDetector mouseDetector; private ScaleGestureDetector zoomDetector; private View mouseWheelPanel; private GestureDetector mouseWheelDetector; private ButtonView buttonView; public static Paint mPaint; // private MaskFilter mEmboss; // private MaskFilter mBlur; public static int textCol; public static int backCol; public static int mousepadCol; public static int mousewheelCol; private ServiceConnection pingServiceConnection; private Security security; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { security = new Security(Preferences.getInstance(this).getPassword()); } catch (Exception ex) { debug(ex.toString()); } // Should remember all button states? mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setDither(true); mPaint.setColor(0xFFFF0000); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeJoin(Paint.Join.ROUND); mPaint.setStrokeCap(Paint.Cap.ROUND); mPaint.setStrokeWidth(12); // mEmboss = new EmbossMaskFilter(new float[] { 1, 1, 1 }, // 0.4f, 6, 3.5f); // mBlur = new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL); last_up = 0; // try { // Get an instance of the SensorManager mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); // Get an instance of the PowerManager mPowerManager = (PowerManager) getSystemService(POWER_SERVICE); // Create a bright wake lock wl = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, getClass().getName()); // wl.setReferenceCounted(false); // Get an instance of the WindowManager mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE); mDisplay = mWindowManager.getDefaultDisplay(); mWifiManager = (WifiManager) getSystemService(WIFI_SERVICE); // Create a Wifi wakelock wifiLock = mWifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "MyWifiLock"); if (!wifiLock.isHeld()) { wifiLock.acquire(); } mAccelerometer = mSensorManager .getDefaultSensor(Sensor.TYPE_ACCELEROMETER); nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); vibrateNotification = new Notification(); vibrateNotification.vibrate = new long[] { 0, 40 }; mySharedPreferences = getSharedPreferences("MY_PREFS", Activity.MODE_PRIVATE); keyState = new int[MAX_KEYS]; x1Pos = new int[MAX_KEYS]; y1Pos = new int[MAX_KEYS]; x2Pos = new int[MAX_KEYS]; y2Pos = new int[MAX_KEYS]; for (int i = 0; i < MAX_KEYS; i++) { keyState[i] = KEY_STATE_UP; } // Store available actions. Used when editing layouts. number_of_keycodes = storeActions(); EDIT_Names = new String[number_of_keycodes]; for (int i = 0; i < number_of_keycodes; i++) { // debug(getActionName(key_actions[i])); EDIT_Names[i] = Constants.getActionName(key_actions[i]); } reload_settings(); debug("onCreate - layout_mode_pos: " + layout_mode_pos); setDefaultKeys(); layout_action = new LinearLayout(this); layout_action.setOrientation(LinearLayout.VERTICAL); action_text = new TextView(this); action_text.setText("Choose action:"); edCmd = new EditText(this); edCmd.addTextChangedListener(new TextWatcherAdapter() { @Override public void afterTextChanged(Editable s) { Preferences.getInstance(getApplicationContext()) .setKeyCustomCommand(key_to_edit, s.toString()); } }); choose_action = new ListView(this); choose_action.setChoiceMode(ListView.CHOICE_MODE_SINGLE); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, EDIT_Names); choose_action.setClickable(true); choose_action.setOnItemClickListener(this); choose_action.setAdapter(adapter); choose_action.setTextFilterEnabled(true); layout_action.addView(action_text); layout_action.addView(edCmd); layout_action.addView(choose_action); layout_select = new LinearLayout(this); layout_select.setOrientation(LinearLayout.VERTICAL); layout_text = new TextView(this); layout_text.setText("Choose layout:"); choose_layout = new ListView(this); choose_layout.setChoiceMode(ListView.CHOICE_MODE_SINGLE); ArrayAdapter<String> adapter_layout = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, LAYOUT_Names); choose_layout.setClickable(true); choose_layout.setOnItemClickListener(this); choose_layout.setAdapter(adapter_layout); choose_layout.setTextFilterEnabled(true); layout_select.addView(layout_text); layout_select.addView(choose_layout); sendLanguage(); showMainView(); } private void showMainView() { setContentView(R.layout.layout_view); setupGui(); } @Override protected void onStart() { super.onStart(); startPing(); } private void setupGui() { mousePanel = (View) findViewById(R.id.mousePanel); mouseWheelPanel = (View) findViewById(R.id.mouseWheelPanel); mouseDetector = getMouseDetector(); zoomDetector = getZoomDetector(); mouseWheelDetector = getMouseWheelDetector(); mousePanel.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (mouseDetector.onTouchEvent(event)) { return true; } else { return zoomDetector.onTouchEvent(event); } } }); mouseWheelPanel.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return mouseWheelDetector.onTouchEvent(event); } }); buttonView = (ButtonView) findViewById(R.id.buttonView); registerForContextMenu(buttonView); buttonView .setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() { @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.button_edit_menu, menu); final AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; if (Preferences .getInstance(MouseKeysRemote.this) .isButtonSticky( Integer.valueOf( ((Button) info.targetView) .getTag(R.id.button_id) .toString()).intValue())) { menu.findItem(R.id.mnuSticky).setChecked(true); } } }); buttonView.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { Button b = (Button) v; boolean sticky = Boolean.valueOf(b.getTag(R.id.button_sticky) .toString()); String cmd = Preferences.getInstance(getApplicationContext()) .getKeyCustomCommand( Integer.valueOf(b.getTag(R.id.button_id) .toString())); switch (event.getAction()) { case KeyEvent.ACTION_DOWN: if (cmd.equals("")) { if (!sticky) sendUDP(Constants.getActionPress(keyCode)); } else { sendUDP(cmd); } vibrate(); return true; case KeyEvent.ACTION_UP: if (cmd.equals("")) { if (sticky) { if (b.isPressed()) sendUDP(Constants.getActionPress(keyCode)); else sendUDP(Constants.getActionRelease(keyCode)); } else sendUDP(Constants.getActionRelease(keyCode)); } return true; } return false; } private void vibrate() { if (enableVibrate) { nm.notify(1, vibrateNotification); } } }); } private void startPing() { pingServiceConnection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { } @Override public void onServiceConnected(ComponentName name, IBinder service) { } }; Intent intent = new Intent(this, PingService.class); bindService(intent, pingServiceConnection, Context.BIND_AUTO_CREATE); } private GestureDetector getMouseDetector() { return new GestureDetector( new GestureDetector.SimpleOnGestureListener() { @Override public boolean onDoubleTap(MotionEvent e) { return false; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { if (e1.getPointerCount() > 1 || e2.getPointerCount() > 1) return false; if (distanceX != 0) { // Only move if there has been a // movement String msg = "XMM" + (int) -distanceX * (mouse_speed_pos + 1); sendUDP(msg); } if (distanceY != 0) { // Only move if there has been a // movement String msg = "YMM" + (int) -distanceY * (mouse_speed_pos + 1); sendUDP(msg); } return true; } @Override public boolean onSingleTapConfirmed(MotionEvent e) { if (e.getPointerCount() > 1) return false; if (enableClickOnTap) { String msg = "MLC"; sendUDP(msg); msg = "MLR"; sendUDP(msg); if (enableVibrate) { nm.notify(1, vibrateNotification); } return true; } return false; } }); } private ScaleGestureDetector getZoomDetector() { return new ScaleGestureDetector(this, new SimpleOnScaleGestureListener() { @Override public boolean onScale(ScaleGestureDetector detector) { if (enablePinchZoom && detector.getScaleFactor() != 1) { int zoom_diff = (int) (detector.getCurrentSpan() - detector .getPreviousSpan()); String msg = "MPZ" + zoom_diff; // Mouse Pinch // Zoom.. Positive // values means zoom // in and // negative zoom // out. sendUDP(msg); return true; } return false; } }); } private GestureDetector getMouseWheelDetector() { return new GestureDetector( new GestureDetector.SimpleOnGestureListener() { @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { if (Math.abs(distanceY) > Math.abs(distanceX)) { int newAccY = (int) (distanceY / 6); if (newAccY != 0) { sendUDP("MWS" + newAccY); } else {// Make sure that something happens even for // small movements if (distanceY > 0) { sendUDP("MWS1"); } else { sendUDP("MWS-1"); } } } else { return true; } return false; } }); } private int storeActions() { key_actions = new int[200]; key_actions[0] = Constants.CUR_RIGHT; key_actions[1] = Constants.CUR_LEFT; key_actions[2] = Constants.CUR_UP; key_actions[3] = Constants.CUR_DOWN; key_actions[4] = Constants.MOUSE_RIGHT; key_actions[5] = Constants.MOUSE_LEFT; key_actions[6] = Constants.MOUSE_UP; key_actions[7] = Constants.MOUSE_DOWN; key_actions[8] = Constants.MOUSE_LCLICK; key_actions[9] = Constants.MOUSE_RCLICK; key_actions[10] = Constants.ESC; key_actions[11] = Constants.CR; key_actions[12] = Constants.NUM_KP_0; key_actions[13] = Constants.NUM_KP_1; key_actions[14] = Constants.NUM_KP_2; key_actions[15] = Constants.NUM_KP_3; key_actions[16] = Constants.NUM_KP_4; key_actions[17] = Constants.NUM_KP_5; key_actions[18] = Constants.NUM_KP_6; key_actions[19] = Constants.NUM_KP_7; key_actions[20] = Constants.NUM_KP_8; key_actions[21] = Constants.NUM_KP_9; key_actions[22] = Constants.SPACE; key_actions[23] = Constants.MOUSE_WUP; key_actions[24] = Constants.MOUSE_WDOWN; key_actions[25] = Constants.F1; key_actions[26] = Constants.F2; key_actions[27] = Constants.F3; key_actions[28] = Constants.F4; key_actions[29] = Constants.F5; key_actions[30] = Constants.F6; key_actions[31] = Constants.F7; key_actions[32] = Constants.F8; key_actions[33] = Constants.F9; key_actions[34] = Constants.F10; key_actions[35] = Constants.F11; key_actions[36] = Constants.F12; key_actions[37] = Constants.LCTRL; key_actions[38] = Constants.DEL; key_actions[39] = Constants.LSHIFT; key_actions[40] = Constants.LALT; key_actions[41] = Constants.INS; key_actions[42] = Constants.CHRA; key_actions[43] = Constants.CHRB; key_actions[44] = Constants.CHRC; key_actions[45] = Constants.CHRD; key_actions[46] = Constants.CHRE; key_actions[47] = Constants.CHRF; key_actions[48] = Constants.CHRG; key_actions[49] = Constants.CHRH; key_actions[50] = Constants.CHRI; key_actions[51] = Constants.CHRJ; key_actions[52] = Constants.CHRK; key_actions[53] = Constants.CHRL; key_actions[54] = Constants.CHRM; key_actions[55] = Constants.CHRN; key_actions[56] = Constants.CHRO; key_actions[57] = Constants.CHRP; key_actions[58] = Constants.CHRQ; key_actions[59] = Constants.CHRR; key_actions[60] = Constants.CHRS; key_actions[61] = Constants.CHRT; key_actions[62] = Constants.CHRU; key_actions[63] = Constants.CHRV; key_actions[64] = Constants.CHRW; key_actions[65] = Constants.CHRX; key_actions[66] = Constants.CHRY; key_actions[67] = Constants.CHRZ; key_actions[68] = Constants.CHR0; key_actions[69] = Constants.CHR1; key_actions[70] = Constants.CHR2; key_actions[71] = Constants.CHR3; key_actions[72] = Constants.CHR4; key_actions[73] = Constants.CHR5; key_actions[74] = Constants.CHR6; key_actions[75] = Constants.CHR7; key_actions[76] = Constants.CHR8; key_actions[77] = Constants.CHR9; key_actions[78] = Constants.PLUS; key_actions[79] = Constants.MINUS; key_actions[80] = Constants.TAB; key_actions[81] = Constants.PGUP; key_actions[82] = Constants.PGDOWN; key_actions[83] = Constants.COMMA; key_actions[84] = Constants.PERIOD; key_actions[85] = Constants.END; key_actions[86] = Constants.HOME; key_actions[87] = Constants.BACKSPACE; key_actions[88] = Constants.DUMMY; key_actions[89] = Constants.SEMI_COLON; key_actions[90] = Constants.BACKSLASH; key_actions[91] = Constants.AT; key_actions[92] = Constants.SLASH; key_actions[93] = Constants.COLON; key_actions[94] = Constants.EQUALS; key_actions[95] = Constants.QUESTION; key_actions[96] = Constants.ZOOM_IN; key_actions[97] = Constants.ZOOM_OUT; key_actions[98] = Constants.ZOOM_RESET; key_actions[99] = Constants.NORTH; key_actions[100] = Constants.SOUTH; key_actions[101] = Constants.WEST; key_actions[102] = Constants.EAST; key_actions[103] = Constants.NORTHWEST; key_actions[104] = Constants.NORTHEAST; key_actions[105] = Constants.SOUTHWEST; key_actions[106] = Constants.SOUTHEAST; return key_actions.length; } @Override protected void onStop() { debug("onStop"); release_locks(); stopSensors(); super.onStop(); } private void release_locks() { if (wl.isHeld()) { wl.release(); } if (wifiLock.isHeld()) { wifiLock.release(); } } @Override protected void onDestroy() { debug("onDestroy"); release_locks(); stopSensors(); unbindService(pingServiceConnection); super.onDestroy(); } @Override protected void onResume() { debug("onResume"); super.onResume(); /* * when the activity is resumed, we acquire a wake-lock so that the * screen stays on, since the user will likely not be fiddling with the * screen or buttons. */ // mWakeLock.acquire(); set_locks(); sendLanguage(); accXFloatOld = 0; accYFloatOld = 0; last_up = 0; if (enableSensors) { // Activate sensors if (sensors_mode == SENSORS_MOUSE_GAME && (enableSensorsX || enableSensorsY)) { sendUDP("MMC"); // Center mouse } mSensorManager.registerListener(this, mAccelerometer, DEFAULT_SENSOR_DELAY); } else { stopSensors(); } } private void set_locks() { if (enableAlwaysOn) { if (!wl.isHeld()) { wl.acquire(); } } if (!wifiLock.isHeld()) { wifiLock.acquire(); } } @Override protected void onPause() { debug("onPause"); super.onPause(); /* * When the activity is paused, we make sure to stop the simulation, * release our sensor resources and wake locks */ stopSensors(); // and release our wake-lock release_locks(); // mWakeLock.release(); } void stopSensors() { mSensorManager.unregisterListener(this); if (sensors_mode == SENSORS_CURSOR) { if (sensorStateX == ROTATE_X_LEFT) { // stop left sendUDP("KBR" + 37); } else if (sensorStateX == ROTATE_X_RIGHT) { // stop right sendUDP("KBR" + 39); } if (sensorStateY == ROTATE_Y_FORWARD) { // stop forward sendUDP("KBR" + 38); } else if (sensorStateY == ROTATE_Y_BACK) { // stop back sendUDP("KBR" + 40); } } else if (sensors_mode == SENSORS_MOUSE && (enableSensorsX || enableSensorsY)) { sendUDP("MSR"); sendUDP("MSL"); sendUDP("MSU"); sendUDP("MSD"); } } @Override public void onSensorChanged(SensorEvent event) { // debug(event.toString()); if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER) return; /* * record the accelerometer data, the event's timestamp as well as the * current time. The latter is needed so we can calculate the "present" * time during rendering. In this application, we need to take into * account how the screen is rotated with respect to the sensors (which * always return data in a coordinate space aligned to with the screen * in its native orientation). */ // debug(event.toString()); /* * debug("-------"); debug(event.values[0]); debug(event.values[1]); * debug(event.values[2]); debug("-------"); */ // mSensorZ = event.values[2]; switch (mDisplay.getOrientation()) { case Surface.ROTATION_0: // debug("0"); mSensorX = event.values[0]; mSensorY = -event.values[1]; break; case Surface.ROTATION_90: // debug("90"); mSensorX = -event.values[1]; mSensorY = -event.values[0]; break; case Surface.ROTATION_180: // debug("180"); mSensorX = -event.values[0]; mSensorY = event.values[1]; break; case Surface.ROTATION_270: // debug("270"); mSensorX = event.values[1]; mSensorY = event.values[0]; break; } // debug("mSensorX: " + mSensorX + " mSensorY: " + mSensorY + // " mSensorZ: " + mSensorZ); if (calibrate == true) { calibrate_x = mSensorX; calibrate_y = mSensorY; } else { if (sensors_mode == SENSORS_MOUSE_GAME) { sensorsMoveMouse(); } else { sensorsMoveCursorOrMouse(); } } } void sensorsMoveMouse() { // debug("Move mouse"); /* * Kolla om ändring av X eller Y, om större än 0 flytta musen. Skala * upp sensorvärdena med faktor 5? Utgångsvärden alltid lika med * värden för plant läge. Behövs manuell kalibreringsfunktion. Kolla * flera värden på raken för att få ett stabilt? */ accXFloat = -(mSensorX - calibrate_x) * 5; accYFloat = -(mSensorY - calibrate_y) * 5; // debug("xPosFirstFloat:" + xPosFirstFloat + " yPosFirstFloat:" + // yPosFirstFloat); // debug("accXFloat:" + accXFloat + " accYFloat:" + accYFloat); // Calculate any change in distance accXFloatDiff = -(accXFloatOld - accXFloat); accYFloatDiff = -(accYFloatOld - accYFloat); // Convert change in distance to int accX = (int) accXFloatDiff; accY = (int) accYFloatDiff; // debug("accX:" + accX + " accY:" + accY); if (accX != 0 && enableSensorsX) // Only move if there has been a // movement! { // store new distance accXFloatOld = accXFloat; // debug("accX: "+ accX); String msg = "XMM" + accX * (mouse_speed_pos + 1); // debug("UDP msg: " + msg); sendUDP(msg); // store new distance } if (accY != 0 && enableSensorsY) // Only move if there has been a // movement! { accYFloatOld = accYFloat; // debug("accY: "+ accY); String msg = "YMM" + accY * (mouse_speed_pos + 1); // debug("UDP msg: " + msg); sendUDP(msg); } } void sensorsMoveCursorOrMouse() { if (mSensorX - calibrate_x > (sensorRotateLeft + sensorHysteris) && enableSensorsX) { // debug("Left"); if (sensorStateX == ROTATE_X_NONE) { // start left if (sensors_mode == SENSORS_MOUSE) { sendUDP("MML"); } else { sendUDP("KBP" + 37); } } else if (sensorStateX == ROTATE_X_RIGHT) { // stop right and start left if (sensors_mode == SENSORS_MOUSE) { sendUDP("MSR"); sendUDP("MML"); } else { sendUDP("KBR" + 39); sendUDP("KBP" + 37); } } sensorStateX = ROTATE_X_LEFT; } else if (mSensorX - calibrate_x > sensorRotateLeft && mSensorX <= (sensorRotateLeft + sensorHysteris)) { // debug("ignorning left hysteresis"); } else if (mSensorX - calibrate_x < (sensorRotateRight - sensorHysteris) && enableSensorsX) { // debug("Right"); if (sensorStateX == ROTATE_X_NONE) { // start right if (sensors_mode == SENSORS_MOUSE) { sendUDP("MMR"); } else { sendUDP("KBP" + 39); } } else if (sensorStateX == ROTATE_X_LEFT) { // stop left and start right if (sensors_mode == SENSORS_MOUSE) { sendUDP("MSL"); sendUDP("MMR"); } else { sendUDP("KBR" + 37); sendUDP("KBP" + 39); } } sensorStateX = ROTATE_X_RIGHT; } else if (mSensorX - calibrate_x < sensorRotateRight && mSensorX >= (sensorRotateRight - sensorHysteris)) { // debug("ignorning right hysteresis"); } else if (enableSensorsX) { // debug("CenterX"); if (sensorStateX == ROTATE_X_LEFT) { // stop left // debug("CenterX"); if (sensors_mode == SENSORS_MOUSE) { sendUDP("MSL"); } else { sendUDP("KBR" + 37); } } else if (sensorStateX == ROTATE_X_RIGHT) { // stop right // debug("CenterX"); if (sensors_mode == SENSORS_MOUSE) { sendUDP("MSR"); } else { sendUDP("KBR" + 39); } } sensorStateX = ROTATE_X_NONE; } if (mSensorY - calibrate_y > sensorOffsetY + (sensorRotateForward + sensorHysteris) && enableSensorsY) { // debug("Forward"); if (sensorStateY == ROTATE_Y_NONE) { // start forward if (sensors_mode == SENSORS_MOUSE) { sendUDP("MMU"); } else { sendUDP("KBP" + 38); } } else if (sensorStateY == ROTATE_Y_BACK) { // stop back and start forward if (sensors_mode == SENSORS_MOUSE) { sendUDP("MSD"); sendUDP("MMU"); } else { sendUDP("KBR" + 40); sendUDP("KBP" + 38); } } sensorStateY = ROTATE_Y_FORWARD; } else if (mSensorY - calibrate_y > sensorOffsetY + sensorRotateForward && mSensorY <= sensorOffsetY + (sensorRotateForward + sensorHysteris)) { // debug("ignorning forward hysteris"); } else if (mSensorY - calibrate_y < sensorOffsetY + (sensorRotateBack - sensorHysteris) && enableSensorsY) { // debug("Back"); if (sensorStateY == ROTATE_Y_NONE) { // start back if (sensors_mode == SENSORS_MOUSE) { sendUDP("MMD"); } else { sendUDP("KBP" + 40); } } else if (sensorStateY == ROTATE_Y_FORWARD) { // stop forward and start back if (sensors_mode == SENSORS_MOUSE) { sendUDP("MSU"); sendUDP("MMD"); } else { sendUDP("KBR" + 38); sendUDP("KBP" + 40); } } sensorStateY = ROTATE_Y_BACK; } else if (mSensorY - calibrate_y < sensorOffsetY + sensorRotateBack && mSensorY >= sensorOffsetY + (sensorRotateBack - sensorHysteris)) { // debug("ignorning back hysteris"); } else if (enableSensorsY) { // debug("CenterY"); if (sensorStateY == ROTATE_Y_FORWARD) { // stop forward // debug("CenterY"); if (sensors_mode == SENSORS_MOUSE) { sendUDP("MSU"); } else { sendUDP("KBR" + 38); } } else if (sensorStateY == ROTATE_Y_BACK) { // stop back // debug("CenterY"); if (sensors_mode == SENSORS_MOUSE) { sendUDP("MSD"); } else { sendUDP("KBR" + 40); } } sensorStateY = ROTATE_Y_NONE; } } void setDefaultKeys() { SharedPreferences.Editor editor = mySharedPreferences.edit(); if (!mySharedPreferences.contains("layout" + keys_layout + "key1")) { // Set default values if layouts are empty editor.putInt("layout" + keys_layout + "key1", Constants.ESC); editor.putInt("layout" + keys_layout + "key2", Constants.LCTRL); editor.putInt("layout" + keys_layout + "key3", Constants.CUR_UP); editor.putInt("layout" + keys_layout + "key4", Constants.CR); editor.putInt("layout" + keys_layout + "key5", Constants.SPACE); editor.putInt("layout" + keys_layout + "key6", Constants.CUR_LEFT); editor.putInt("layout" + keys_layout + "key7", Constants.DUMMY); editor.putInt("layout" + keys_layout + "key8", Constants.CUR_RIGHT); editor.putInt("layout" + keys_layout + "key9", Constants.TAB); editor.putInt("layout" + keys_layout + "key10", Constants.MOUSE_UP); editor.putInt("layout" + keys_layout + "key11", Constants.CUR_DOWN); editor.putInt("layout" + keys_layout + "key12", Constants.PLUS); editor.putInt("layout" + keys_layout + "key13", Constants.MOUSE_LEFT); editor.putInt("layout" + keys_layout + "key14", Constants.DUMMY); editor.putInt("layout" + keys_layout + "key15", Constants.MOUSE_RIGHT); editor.putInt("layout" + keys_layout + "key16", Constants.MINUS); editor.putInt("layout" + keys_layout + "key17", Constants.MOUSE_LCLICK); editor.putInt("layout" + keys_layout + "key18", Constants.MOUSE_DOWN); editor.putInt("layout" + keys_layout + "key19", Constants.MOUSE_RCLICK); editor.putInt("layout" + keys_layout + "key20", Constants.DUMMY); editor.commit(); } } /** Creates the menu items **/ @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, MENU_MAIN, 0, "Virtual keyboard"); menu.add(0, MENU_KP_TOUCH, 0, "Mouse/Keypad"); menu.add(0, MENU_UNHIDE, 0, getResources().getString(R.string.unhide_all)); menu.add(0, MENU_LAYOUT, 0, "Select layout"); menu.add(0, MENU_STICK, 0, "Toggle sticky keys"); menu.add(0, MENU_MORE, 0, "Settings"); menu.add(0, MENU_CALIBRATE, 0, "Calibrate sensors"); menu.add(0, MENU_ABOUT, 0, "About"); menu.add(0, MENU_QUIT, 0, "Exit"); return true; } /* Handles item selections */ public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_MAIN: // Virtual keyboard... setContentView(R.layout.main); EditText sendtext = (EditText) findViewById(R.id.keyboard_input); sendtext.setText(""); sendtext.requestFocusFromTouch(); sendtext.requestFocus(); sendtext.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { if (count - before > 0) { // Char added char ch = s.charAt(start + count - 1); sendUDP("KBP" + (int) ch); sendUDP("KBR" + (int) ch); } else if (before - count == 1) { // Backspace sendUDP("KBP" + 8); sendUDP("KBR" + 8); } } }); InputMethodManager inputMgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputMgr.toggleSoftInput(0, 0); return true; case MENU_KP_TOUCH: sendLanguage(); showMainView(); return true; case MENU_EDIT: if (edit == EditMode.None) edit = EditMode.Binding; else if (edit == EditMode.Binding) edit = EditMode.Name; else if (edit == EditMode.Name) edit = EditMode.Color; else if (edit == EditMode.Color) edit = EditMode.None; if (sticky) keyPadView.setMark(EditMode.Sticky); else keyPadView.setMark(edit); showMainView(); return true; case MENU_ABOUT: setContentView(R.layout.info); return true; case MENU_COLOR: // showColorPicker(mPaint.getColor()); return true; case MENU_QUIT: quit(); return true; case MENU_CALIBRATE: debug("calibrate"); calibrate = true; showMainView(); return true; case MENU_LAYOUT: setContentView(layout_select); for (int i = 0; i < DEFAULT_LAYOUTS; i++) { LAYOUT_Names3[i] = mySharedPreferences.getString( "layout_name" + i, "Layout " + (i + 1)); } ArrayAdapter<String> adapter_layout = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, LAYOUT_Names3); choose_layout.setAdapter(adapter_layout); return true; case MENU_MORE: setContentView(R.layout.settings); try { spinner = (Spinner) findViewById(R.id.spinner); ArrayAdapter<CharSequence> adapter_lang = ArrayAdapter .createFromResource(this, R.array.lang_array, android.R.layout.simple_spinner_item); adapter_lang .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter_lang); spinner.setSelection(lang_pos, true); spinner.setOnItemSelectedListener(this); } catch (Exception e) { debug(e.toString()); } try { mouse_spinner = (Spinner) findViewById(R.id.mouse_spinner); ArrayAdapter<CharSequence> adapter_mouse = ArrayAdapter .createFromResource(this, R.array.mouse_speed_array, android.R.layout.simple_spinner_item); adapter_mouse .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mouse_spinner.setAdapter(adapter_mouse); mouse_spinner.setSelection(mouse_speed_pos); mouse_spinner.setOnItemSelectedListener(this); } catch (Exception e) { debug(e.toString()); } try { layout_mode_spinner = (Spinner) findViewById(R.id.layout_mode_spinner); ArrayAdapter<CharSequence> adapter_layout_mode = ArrayAdapter .createFromResource(this, R.array.layout_mode_array, android.R.layout.simple_spinner_item); adapter_layout_mode .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); layout_mode_spinner.setAdapter(adapter_layout_mode); layout_mode_spinner.setSelection(layout_mode_pos); layout_mode_spinner.setOnItemSelectedListener(this); } catch (Exception e) { debug(e.toString()); } TextView lang_text = (TextView) findViewById(R.id.keyboard_lang); TextView mouse_speed_text = (TextView) findViewById(R.id.mouse_speed); EditText ed = (EditText) findViewById(R.id.entry_ip); EditText port_ed = (EditText) findViewById(R.id.entry_port); EditText mousepadentry = (EditText) findViewById(R.id.mousepadentry); EditText colsentry = (EditText) findViewById(R.id.entry_kpcols); EditText rowsentry = (EditText) findViewById(R.id.entry_kprows); EditText passentry = (EditText) findViewById(R.id.password_entry); EditText layoutentry = (EditText) findViewById(R.id.layout_entry); EditText textSizeEntry = (EditText) findViewById(R.id.entry_text_size); CheckBox mousewheel = (CheckBox) findViewById(R.id.mousewheel); CheckBox vibrate = (CheckBox) findViewById(R.id.vibrate); CheckBox mousepad = (CheckBox) findViewById(R.id.mousepad); CheckBox always_on = (CheckBox) findViewById(R.id.always_on); CheckBox sensors = (CheckBox) findViewById(R.id.sensors); CheckBox sensors_x = (CheckBox) findViewById(R.id.sensors_x); CheckBox sensors_y = (CheckBox) findViewById(R.id.sensors_y); CheckBox clickontap = (CheckBox) findViewById(R.id.clickontap); CheckBox pinchzoom = (CheckBox) findViewById(R.id.pinch_zoom); RadioButton sensors_cursor = (RadioButton) findViewById(R.id.sensors_cursor); RadioButton sensors_mouse = (RadioButton) findViewById(R.id.sensors_mouse); RadioButton sensors_mouse_game = (RadioButton) findViewById(R.id.sensors_mouse_game); // mouse_speed_text.setText("Mouse speed (" + // mouse_spinner.getItemAtPosition(mouse_speed_pos).toString() + // ")"); // lang_text.setText("PC keyboard type (" + // spinner.getItemAtPosition(lang_pos).toString() + ")"); Button text_col = (Button) findViewById(R.id.textcol); text_col.setBackgroundColor(textCol); Button back_col = (Button) findViewById(R.id.background_col); back_col.setBackgroundColor(backCol); Button mousepad_col = (Button) findViewById(R.id.mousepad_col); mousepad_col.setBackgroundColor(mousepadCol); Button mousewheel_col = (Button) findViewById(R.id.mousewheel_col); mousewheel_col.setBackgroundColor(mousewheelCol); text_col.setOnClickListener(this); back_col.setOnClickListener(this); mousepad_col.setOnClickListener(this); mousewheel_col.setOnClickListener(this); ed.setText(host); ed.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { host = (s.toString()).trim(); SharedPreferences.Editor editor = mySharedPreferences .edit(); editor.putString("host", host); editor.commit(); } }); port_ed.setText("" + port); port_ed.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { // debug("e3"); // debug(s.toString() + " start: " + start + " before: " // + // before + " count: " + count); try { int val = Integer.parseInt((s.toString()).trim()); if (val >= 0 & val <= 65535) { port = val; SharedPreferences.Editor editor = mySharedPreferences .edit(); editor.putInt("port", port); editor.commit(); } } catch (Exception e) { debug(e.toString()); } } }); passentry.setText(passwd); passentry.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { passwd = (s.toString()).trim(); SharedPreferences.Editor editor = mySharedPreferences .edit(); editor.putString("password", passwd); try { security = new Security(passwd); } catch (Exception ex) { debug(ex.toString()); } editor.commit(); } }); mousepadentry.setText("" + mousepadRelativeSize); mousepadentry.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { try { int val = Integer.parseInt((s.toString()).trim()); if (val >= 0 & val <= 100) { mousepadRelativeSize = val; SharedPreferences.Editor editor = mySharedPreferences .edit(); editor.putInt("mousepadRelativeSize" + keys_layout, mousepadRelativeSize); editor.commit(); keyPadView.postInvalidate(); } } catch (Exception e) { debug(e.toString()); } } }); colsentry.setText("" + numberOfKeyCols); colsentry.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { try { int val = Integer.parseInt((s.toString()).trim()); if (val >= 0 & val <= 100 & (val * numberOfKeyRows < 200)) { numberOfKeyCols = val; SharedPreferences.Editor editor = mySharedPreferences .edit(); editor.putInt("numberOfKeyCols" + keys_layout, numberOfKeyCols); editor.commit(); keyPadView.postInvalidate(); } } catch (Exception e) { debug(e.toString()); } } }); rowsentry.setText("" + numberOfKeyRows); rowsentry.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { try { int val = Integer.parseInt((s.toString()).trim()); if (val >= 0 & val <= 100 & (val * numberOfKeyCols < 200)) { numberOfKeyRows = val; SharedPreferences.Editor editor = mySharedPreferences .edit(); editor.putInt("numberOfKeyRows" + keys_layout, numberOfKeyRows); editor.commit(); keyPadView.postInvalidate(); } } catch (Exception e) { debug(e.toString()); } } }); textSizeEntry.setText("" + textSize); textSizeEntry.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { try { float val = Float.parseFloat((s.toString()).trim()); if (val > 0) { textSize = val; SharedPreferences.Editor editor = mySharedPreferences .edit(); editor.putFloat("textSize" + keys_layout, textSize); editor.commit(); keyPadView.postInvalidate(); } } catch (Exception e) { debug(e.toString()); } } }); layoutentry.setText(keys_layout_name); layoutentry.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { keys_layout_name = (s.toString()).trim(); SharedPreferences.Editor editor = mySharedPreferences .edit(); editor.putString("layout_name" + keys_layout, keys_layout_name); editor.commit(); keyPadView.postInvalidate(); } }); mousepad.setChecked(enableMousePad); mousepad.setOnClickListener(this); mousewheel.setChecked(enableMouseWheel); mousewheel.setOnClickListener(this); vibrate.setChecked(enableVibrate); vibrate.setOnClickListener(this); always_on.setChecked(enableAlwaysOn); always_on.setOnClickListener(this); sensors.setChecked(enableSensors); sensors.setOnClickListener(this); sensors_x.setChecked(enableSensorsX); sensors_x.setOnClickListener(this); sensors_y.setChecked(enableSensorsY); sensors_y.setOnClickListener(this); clickontap.setChecked(enableClickOnTap); clickontap.setOnClickListener(this); pinchzoom.setChecked(enablePinchZoom); pinchzoom.setOnClickListener(this); // send = (Button)findViewById(R.id.send); // send.setOnClickListener(this); if (sensors_mode == SENSORS_MOUSE) { sensors_mouse.setChecked(true); } else if (sensors_mode == SENSORS_MOUSE_GAME) { sensors_mouse_game.setChecked(true); } else { sensors_cursor.setChecked(true); } sensors_cursor.setOnClickListener(this); sensors_mouse.setOnClickListener(this); sensors_mouse_game.setOnClickListener(this); return true; case MENU_STICK: sticky = !sticky; showMainView(); return true; case MENU_UNHIDE: buttonView.unhideAll(); return true; } return false; } private void sendLanguage() { String msg = "LNG" + lang_pos; // debug("UDP msg: " + msg); sendUDP(msg); } void quit() { this.finish(); } public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { debug(parent.getItemAtPosition(pos).toString()); debug(parent.toString()); // Toast.makeText(parent.getContext(), "The planet is " + // parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show(); if (parent == spinner) { debug("lang"); lang_pos = pos; SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putInt("lang_pos", lang_pos); editor.commit(); sendLanguage(); } else if (parent == mouse_spinner) { debug("mouse"); mouse_speed_pos = pos; SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putInt("mouse_speed_pos" + keys_layout, mouse_speed_pos); editor.commit(); } else if (parent == layout_mode_spinner) { debug("layout_mode"); layout_mode_pos = pos; debug(pos); SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putInt("layout_mode_pos" + keys_layout, layout_mode_pos); editor.commit(); setOrientation(); } } // Events from keyboard // Implement the OnKeyDown callback public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: { debug("back"); sendLanguage(); if (findViewById(R.id.layout_view) == null) showMainView(); else quit(); } } return false; } // Events from views // Implement the OnItemClickListener callback public void onItemClick(AdapterView<?> v, View w, int i, long l) { // do something when the button is clicked debug("onItemClick: " + v.toString()); debug("i:" + i + " l:" + l); if (v == choose_action) // Edit key action { debug("choose_action"); debug(Constants.getActionName(key_actions[i])); // SharedPreferences mySharedPreferences = // getSharedPreferences("MY_PREFS", Activity.MODE_PRIVATE); SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putInt("layout" + keys_layout + "key" + key_to_edit, key_actions[i]); editor.commit(); sendLanguage(); showMainView(); } else if (v == choose_layout) // Select layout { debug("choose_layout"); keys_layout = i; SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putInt("layout", i); editor.commit(); reload_settings(); setDefaultKeys(); sendLanguage(); showMainView(); } } private void reload_settings() { // Global values host = mySharedPreferences.getString("host", "192.168.10.184"); port = mySharedPreferences.getInt("port", Constants.UDP_PORT); keys_layout = mySharedPreferences.getInt("layout", 0); lang_pos = mySharedPreferences.getInt("lang_pos", DEFAULT_LANGUAGE); passwd = mySharedPreferences.getString("password", ""); // Values unique per layout keys_layout_name = mySharedPreferences.getString("layout_name" + keys_layout, "Layout " + (keys_layout + 1)); mouse_speed_pos = mySharedPreferences.getInt("mouse_speed_pos" + keys_layout, DEFAULT_MOUSE_ACC - 1); // List index starts at // zero, add one when // using.. numberOfKeyRows = mySharedPreferences.getInt("numberOfKeyRows" + keys_layout, DEFAULT_NUM_ROWS); numberOfKeyCols = mySharedPreferences.getInt("numberOfKeyCols" + keys_layout, DEFAULT_NUM_COLS); mousepadRelativeSize = mySharedPreferences.getInt( "mousepadRelativeSize" + keys_layout, DEFAULT_MP_SIZE); enableMouseWheel = mySharedPreferences.getBoolean("enableMouseWheel" + keys_layout, true); enableVibrate = mySharedPreferences.getBoolean("enableVibrate" + keys_layout, true); enableMousePad = mySharedPreferences.getBoolean("enableMousePad" + keys_layout, true); textSize = mySharedPreferences.getFloat("textSize" + keys_layout, DEFAULT_TEXT_SIZE); enableAlwaysOn = mySharedPreferences.getBoolean("enableAlwaysOn" + keys_layout, false); enableSensors = mySharedPreferences.getBoolean("enableSensors" + keys_layout, false); enableSensorsX = mySharedPreferences.getBoolean("enableSensorsX" + keys_layout, true); enableSensorsY = mySharedPreferences.getBoolean("enableSensorsY" + keys_layout, true); layout_mode_pos = mySharedPreferences.getInt("layout_mode_pos" + keys_layout, 0); sensors_mode = mySharedPreferences.getInt("sensors_mode" + keys_layout, SENSORS_MOUSE); enableClickOnTap = mySharedPreferences.getBoolean("enableClickOnTap" + keys_layout, true); enablePinchZoom = mySharedPreferences.getBoolean("enablePinchZoom" + keys_layout, false); backCol = mySharedPreferences.getInt("background_col" + keys_layout, 0xff000000); textCol = mySharedPreferences.getInt("text_col" + keys_layout, 0xffffffff); mousepadCol = mySharedPreferences.getInt("mousepad_col" + keys_layout, 0xff2222ff); mousewheelCol = mySharedPreferences.getInt("mousewheel_col" + keys_layout, 0xff8888ff); if (enableAlwaysOn) { if (!wl.isHeld()) { wl.acquire(); } } else { if (wl.isHeld()) { wl.release(); } } if (enableSensors) { // Activate sensors mSensorManager.registerListener(this, mAccelerometer, DEFAULT_SENSOR_DELAY); if (sensors_mode == SENSORS_MOUSE_GAME && (enableSensorsX || enableSensorsY)) { sendUDP("MMC"); // Center mouse } } else { stopSensors(); } setOrientation(); } private void setOrientation() { if (layout_mode_pos == 0) { // Auto rotate this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); } else if (layout_mode_pos == 1) { this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } else if (layout_mode_pos == 2) { this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } } // Implement the OnClickListener callback public void onClick(View v) { // do something when the button is clicked debug("onClick:" + v.toString()); CheckBox mousewheel = (CheckBox) findViewById(R.id.mousewheel); CheckBox vibrate = (CheckBox) findViewById(R.id.vibrate); CheckBox mousepad = (CheckBox) findViewById(R.id.mousepad); CheckBox always_on = (CheckBox) findViewById(R.id.always_on); CheckBox sensors = (CheckBox) findViewById(R.id.sensors); CheckBox sensors_x = (CheckBox) findViewById(R.id.sensors_x); CheckBox sensors_y = (CheckBox) findViewById(R.id.sensors_y); RadioButton sensors_cursor = (RadioButton) findViewById(R.id.sensors_cursor); RadioButton sensors_mouse = (RadioButton) findViewById(R.id.sensors_mouse); RadioButton sensors_mouse_game = (RadioButton) findViewById(R.id.sensors_mouse_game); CheckBox clickontap = (CheckBox) findViewById(R.id.clickontap); CheckBox pinchzoom = (CheckBox) findViewById(R.id.pinch_zoom); Button text_col = (Button) findViewById(R.id.textcol); Button back_col = (Button) findViewById(R.id.background_col); Button mousepad_col = (Button) findViewById(R.id.mousepad_col); Button mousewheel_col = (Button) findViewById(R.id.mousewheel_col); if (v == mousewheel) { debug("mousewheel changed"); try { enableMouseWheel = mousewheel.isChecked(); SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putBoolean("enableMouseWheel" + keys_layout, enableMouseWheel); editor.commit(); keyPadView.postInvalidate(); } catch (Exception e) { debug(e.toString()); } } else if (v == vibrate) { debug("vibrate changed"); try { enableVibrate = vibrate.isChecked(); SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putBoolean("enableVibrate" + keys_layout, enableVibrate); editor.commit(); keyPadView.postInvalidate(); } catch (Exception e) { debug(e.toString()); } } else if (v == mousepad) { debug("mousepad changed"); try { enableMousePad = mousepad.isChecked(); SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putBoolean("enableMousePad" + keys_layout, enableMousePad); editor.commit(); keyPadView.postInvalidate(); } catch (Exception e) { debug(e.toString()); } } else if (v == always_on) { debug("always on changed"); if (enableAlwaysOn) { if (wl.isHeld()) { wl.release(); } } else { if (!wl.isHeld()) { wl.acquire(); } } try { enableAlwaysOn = always_on.isChecked(); SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putBoolean("enableAlwaysOn" + keys_layout, enableAlwaysOn); editor.commit(); } catch (Exception e) { debug(e.toString()); } } else if (v == sensors) { debug("sensors changed"); try { enableSensors = sensors.isChecked(); SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putBoolean("enableSensors" + keys_layout, enableSensors); editor.commit(); } catch (Exception e) { debug(e.toString()); } if (enableSensors) { // Activate sensors accXFloatOld = 0; accYFloatOld = 0; mSensorManager.registerListener(this, mAccelerometer, DEFAULT_SENSOR_DELAY); } else { stopSensors(); } } else if (v == sensors_x) { debug("sensors_x changed"); try { enableSensorsX = sensors_x.isChecked(); SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putBoolean("enableSensorsX" + keys_layout, enableSensorsX); editor.commit(); } catch (Exception e) { debug(e.toString()); } if (enableSensorsX) { } else { sendUDP("MSL"); sendUDP("MSR"); } } else if (v == sensors_y) { debug("sensors_y changed"); try { enableSensorsY = sensors_y.isChecked(); SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putBoolean("enableSensorsY" + keys_layout, enableSensorsY); editor.commit(); } catch (Exception e) { debug(e.toString()); } if (enableSensorsY) { } else { sendUDP("MSU"); sendUDP("MSD"); } } else if (v == sensors_mouse) { debug("sensors mouse changed"); sensors_mode = SENSORS_MOUSE; accXFloatOld = 0; accYFloatOld = 0; SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putInt("sensors_mode" + keys_layout, sensors_mode); editor.commit(); } else if (v == sensors_mouse_game) { debug("sensors mouse game changed"); sensors_mode = SENSORS_MOUSE_GAME; accXFloatOld = 0; accYFloatOld = 0; SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putInt("sensors_mode" + keys_layout, sensors_mode); editor.commit(); sendUDP("MMC"); // Center mouse } else if (v == sensors_cursor) { debug("sensors cursor changed"); sendUDP("MSR"); sendUDP("MSL"); sendUDP("MSU"); sendUDP("MSD"); sensors_mode = SENSORS_CURSOR; SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putInt("sensors_mode" + keys_layout, sensors_mode); editor.commit(); } else if (v == clickontap) { debug("clickontap changed"); try { enableClickOnTap = clickontap.isChecked(); SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putBoolean("enableClickOnTap" + keys_layout, enableClickOnTap); editor.commit(); keyPadView.postInvalidate(); } catch (Exception e) { debug(e.toString()); } } else if (v == pinchzoom) { debug("pinchzoom changed"); try { enablePinchZoom = pinchzoom.isChecked(); SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putBoolean("enablePinchZoom" + keys_layout, enablePinchZoom); editor.commit(); keyPadView.postInvalidate(); } catch (Exception e) { debug(e.toString()); } } else if (v == text_col) { showColorPicker(mPaint.getColor(), ColorElement.Text); } else if (v == back_col) { showColorPicker(mPaint.getColor(), ColorElement.Back); } else if (v == mousepad_col) { showColorPicker(mPaint.getColor(), ColorElement.MousePad); } else if (v == mousewheel_col) { showColorPicker(mPaint.getColor(), ColorElement.MouseWheel); } else // catch all, return to menu { debug("catch all, return to menu"); } } private void showColorPicker(int color, ColorElement elem) { Bundle b = new Bundle(); b.putInt(ColorPickerDialog.PROP_INITIAL_COLOR, color); b.putInt(ColorPickerDialog.PROP_PARENT_WIDTH, keyPadView.getMeasuredWidth()); b.putInt(ColorPickerDialog.PROP_PARENT_HEIGHT, keyPadView.getMeasuredHeight()); b.putInt(ColorPickerDialog.PROP_COLORELEM, elem.toInt()); ColorPickerDialog cpd = new ColorPickerDialog(this, b); cpd.setColorChangedListener(this); cpd.show(); } private void display_edit_name_layout() { setContentView(R.layout.edit_key_name); EditText name = (EditText) findViewById(R.id.keyboard_input); name.setText(mySharedPreferences.getString("nameOfKey" + "layout" + keys_layout + "key" + key_to_edit, Constants.getActionName(getKeyValue(key_to_edit)))); name.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { String name = (s.toString()).trim(); SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putString("nameOfKey" + "layout" + keys_layout + "key" + key_to_edit, name); editor.commit(); } }); } static public int getKeyValue(int key_num) { int value = mySharedPreferences.getInt("layout" + keys_layout + "key" + key_num, Constants.DUMMY); return value; } void sendUDP(String msg_plain) { try { String msg = security.encrypt(msg_plain); try { DatagramSocket s = new DatagramSocket(); InetAddress local = InetAddress.getByName(host); int msg_length = msg.length(); byte[] message = msg.getBytes(); DatagramPacket p = new DatagramPacket(message, msg_length, local, port); s.send(p); } catch (Exception e) { debug(e.toString()); } } catch (Exception ex) { Toast.makeText(getApplicationContext(), getString(R.string.security_context_failed_), Toast.LENGTH_LONG).show(); debug(ex.toString()); } } static void debug(String s) { if (debug) Log.d(TAG, s); } static void debug(int i) { if (debug) debug("" + i); } static void debug(float f) { if (debug) debug("" + f); } public void colorChanged_int(int color, ColorElement elem) { mPaint.setColor(color); // int keys_layout = MouseKeysRemote.keys_layout; if (elem == ColorElement.Button) { debug("color: " + color + "key: " + key_to_edit); SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putInt("KeyColor" + "layout" + keys_layout + "key" + key_to_edit, color); editor.commit(); keyPadView.invalidate(); } else if (elem == ColorElement.Text) { debug("text color: " + color + " layout: " + keys_layout); textCol = color; SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putInt("text_col" + keys_layout, color); editor.commit(); keyPadView.postInvalidate(); showMainView(); } else if (elem == ColorElement.Back) { backCol = color; SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putInt("background_col" + keys_layout, color); editor.commit(); keyPadView.postInvalidate(); showMainView(); } else if (elem == ColorElement.MousePad) { mousepadCol = color; SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putInt("mousepad_col" + keys_layout, color); editor.commit(); keyPadView.postInvalidate(); showMainView(); } else if (elem == ColorElement.MouseWheel) { mousewheelCol = color; SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putInt("mousewheel_col" + keys_layout, color); editor.commit(); keyPadView.postInvalidate(); showMainView(); } } @Override public boolean onContextItemSelected(MenuItem item) { final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); key_to_edit = Integer.valueOf( info.targetView.getTag(R.id.button_id).toString()).intValue(); switch (item.getItemId()) { case R.id.mnuCommand: setContentView(layout_action); edCmd.setText(Preferences.getInstance(getApplicationContext()) .getKeyCustomCommand(key_to_edit)); return true; case R.id.mnuLabel: // display_edit_name_layout(); SimpleTextDialog dlg = new SimpleTextDialog(this); dlg.setOnTextChangedListener(new SimpleTextDialog.OnTextChangedListener() { @Override public void onTextChanged(String text) { SharedPreferences.Editor editor = mySharedPreferences .edit(); editor.putString("layout" + keys_layout + "label" + key_to_edit, text); editor.commit(); ((Button) info.targetView).setText(text); } }); dlg.show(getResources().getString(R.string.edit_label), getResources().getString(R.string.name), ((Button) info.targetView).getText().toString()); return true; case R.id.mnuColor: AmbilWarnaDialog cdlg = new AmbilWarnaDialog(this, android.R.color.white, new AmbilWarnaDialog.OnAmbilWarnaListener() { @Override public void onOk(AmbilWarnaDialog dialog, int color) { SharedPreferences.Editor editor = mySharedPreferences .edit(); editor.putInt("KeyColor" + "layout" + keys_layout + "key" + key_to_edit, color); editor.commit(); ((Button) info.targetView).getBackground() .setColorFilter( new LightingColorFilter(color, android.R.color.white)); } @Override public void onCancel(AmbilWarnaDialog dialog) { } }); cdlg.show(); return true; case R.id.mnuSticky: Preferences.getInstance(this).setButtonSticky( key_to_edit, !Preferences.getInstance(this).isButtonSticky( key_to_edit)); return true; case R.id.mnuVisible: Preferences.getInstance(this).setButtonVisible(key_to_edit, false); ((Button) info.targetView).setVisibility(View.INVISIBLE); return true; } return false; } @Override public void colorChanged(int color, int elem) { colorChanged_int(color, ColorElement.valueOf("" + elem)); } @Override public void onAccuracyChanged(Sensor arg0, int arg1) { } @Override public void onNothingSelected(AdapterView<?> arg0) { } }
091420009-dd
src/com/linuxfunkar/mousekeysremote/MouseKeysRemote.java
Java
gpl3
71,004
package com.linuxfunkar.mousekeysremote; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; public class Preferences { private static Preferences preferences; private SharedPreferences prefs; public static Preferences getInstance(Context context) { if (preferences == null) preferences = new Preferences(context); return preferences; } private Preferences(Context context) { prefs = context.getSharedPreferences("MY_PREFS", Activity.MODE_PRIVATE); } public boolean isButtonSticky(int key_num) { return prefs.getBoolean("KeySticky" + "layout" + getLayout() + "key" + key_num, false); } public void setButtonSticky(int key_num, boolean value) { SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean("KeySticky" + "layout" + getLayout() + "key" + key_num, value); editor.commit(); } public boolean isButtonVisible(int key_num) { return prefs.getBoolean("KeyVisible" + "layout" + getLayout() + "key" + key_num, true); } public void setButtonVisible(int key_num, boolean value) { SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean("KeyVisible" + "layout" + getLayout() + "key" + key_num, value); editor.commit(); } public String getHost() { return prefs.getString("host", "192.168.10.184"); } public int getPort() { return prefs.getInt("port", Constants.UDP_PORT); } public String getPassword() { return prefs.getString("password", ""); } public int getLayout() { return prefs.getInt("layout", Constants.DUMMY); } public int getKeyValue(int key_num) { int value = prefs.getInt("layout" + getLayout() + "key" + key_num, Constants.DUMMY); return value; } public String getKeyLabel(int key_num) { return prefs.getString("layout" + getLayout() + "label" + key_num, Constants.getActionName(getKeyValue(key_num))); } public int getKeyColor(int key_num) { return prefs.getInt("KeyColor" + "layout" + getLayout() + "key" + key_num, -1); } public String getKeyCustomCommand(int key_num) { return prefs.getString("KeyCustom" + "layout" + getLayout() + "key" + key_num, ""); } public void setKeyCustomCommand(int key_num, String value) { SharedPreferences.Editor editor = prefs.edit(); editor.putString( "KeyCustom" + "layout" + getLayout() + "key" + key_num, value); editor.commit(); } }
091420009-dd
src/com/linuxfunkar/mousekeysremote/Preferences.java
Java
gpl3
2,474
package com.linuxfunkar.mousekeysremote; import android.text.Editable; import android.text.TextWatcher; public abstract class TextWatcherAdapter implements TextWatcher { @Override public void afterTextChanged(Editable s) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } }
091420009-dd
src/com/linuxfunkar/mousekeysremote/TextWatcherAdapter.java
Java
gpl3
447
/** * @file WrapMotionEvent.java * @brief * * Copyright (C)2010-2012 Magnus Uppman <magnus.uppman@gmail.com> * License: GPLv3+ */ package com.linuxfunkar.mousekeysremote; import android.view.MotionEvent; public class WrapMotionEvent { protected MotionEvent event; protected WrapMotionEvent(MotionEvent event) { this.event = event; } static public WrapMotionEvent wrap(MotionEvent event) { try { //System.out.println("EclairMotionEvent"); return new EclairMotionEvent(event); } catch (VerifyError e) { //System.out.println("WrapMotionEvent"); return new WrapMotionEvent(event); } } public final long getDownTime() { return event.getDownTime(); } public final long getEventTime() { return event.getEventTime(); } public int findPointerIndex(int pointerId) { return 0; } public final int getAction() { return event.getAction(); } public int getPointerCount() { return 1; } public int getPointerId(int pointerIndex) { return 0; } public final float getX() { return event.getX(); } public float getX(int pointerIndex) { return event.getX(); } public final float getY() { return event.getY(); } public float getY(int pointerIndex) { return event.getY(); } public final float getPressure() { return event.getPressure(); } public final float getPressure(int pointerIndex) { return event.getPressure(); } }
091420009-dd
src/com/linuxfunkar/mousekeysremote/WrapMotionEvent.java
Java
gpl3
1,409
package com.linuxfunkar.mousekeysremote; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.nio.charset.Charset; import android.app.Activity; import android.app.Service; import android.content.Intent; import android.content.SharedPreferences; import android.os.Binder; import android.os.Handler; import android.os.IBinder; import android.widget.Toast; public class PingService extends Service { private final IBinder binder = new PingBinder(); private Handler handler; private Runnable timer; private boolean connected = false; @Override public void onCreate() { super.onCreate(); handler = new Handler(); timer = new Runnable() { @Override public void run() { String host = getHost(); int port = getPort(); if (!host.equals("")) { if (!connected) { connected = ping(host, port); if (connected) { Toast.makeText( getApplicationContext(), getString(R.string.connection_established_with) + host + ":" + port, Toast.LENGTH_SHORT).show(); } } else { boolean c = ping(host, port); if (c == false) { Toast.makeText( getApplicationContext(), getString(R.string.connection_lost) + host + ":" + port, Toast.LENGTH_LONG) .show(); } connected = c; } } handler.postDelayed(timer, 10000); } }; handler.postDelayed(timer, 100); } @Override public void onDestroy() { super.onDestroy(); handler.removeCallbacks(timer); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; } @Override public IBinder onBind(Intent arg0) { return binder; } public class PingBinder extends Binder { PingService getService() { return PingService.this; } } private boolean ping(String host, int port) { try { Security security = new Security(Preferences.getInstance(this) .getPassword()); DatagramSocket socket = new DatagramSocket(); socket.connect(new InetSocketAddress(host, port)); byte[] msg = security.encrypt("ping").getBytes("UTF-8"); socket.send(new DatagramPacket(msg, msg.length)); socket.setSoTimeout(5000); DatagramPacket response = new DatagramPacket(msg, 4); socket.receive(response); BufferedReader input = new BufferedReader(new InputStreamReader( new ByteArrayInputStream(response.getData()), Charset.forName("UTF-8"))); String s = input.readLine(); if (!s.startsWith("pong")) { Toast.makeText( getApplicationContext(), getString(R.string.wrong_response_from_server_at) + host + ":" + port, Toast.LENGTH_LONG).show(); } socket.close(); } catch (Exception ex) { Toast.makeText( getApplicationContext(), getString(R.string.connection_failed_with) + host + ":" + port, Toast.LENGTH_LONG).show(); return false; } return true; } private String getHost() { SharedPreferences prefs = getApplicationContext().getSharedPreferences( "MY_PREFS", Activity.MODE_PRIVATE); return prefs.getString("host", ""); } private int getPort() { SharedPreferences prefs = getApplicationContext().getSharedPreferences( "MY_PREFS", Activity.MODE_PRIVATE); return prefs.getInt("port", Constants.UDP_PORT); } }
091420009-dd
src/com/linuxfunkar/mousekeysremote/PingService.java
Java
gpl3
3,574
/** Automatically generated file. DO NOT MODIFY */ package com.linuxfunkar.mousekeysremote; public final class BuildConfig { public final static boolean DEBUG = true; }
091420009-dd
gen/com/linuxfunkar/mousekeysremote/BuildConfig.java
Java
gpl3
173
/* COMPILING: * If you're compiling this with MSVC2010, you'll need to change the include and library directory * paths for opencv to reflect the path on your computer. I think that's all you have to do, but * I may be overlooking something. * * RUNNING: * Several dlls must be in the bin directory for this program to run without error: * opencv_core244.dll * opencv_core244d.dll * opencv_highgui244.dll * opencv_highgui244d.dll * opencv_imgproc244.dll * opencv_imgproc244d.dll * opencv_objdetect244.dll * opencv_objdetect244d.dll */ #include <iostream> #include <opencv2/objdetect/objdetect.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> int main(int argc, char* argv[]) { // Load in the haarcascade file that we'll use for face detection. const std::string FACE_CASCADE_NAME("haarcascade_frontalface_alt.xml"); cv::CascadeClassifier face_cascade(FACE_CASCADE_NAME); if(face_cascade.empty()) { std::cerr << "Failed to load " << FACE_CASCADE_NAME << std::endl; return -1; } // Load in an image containing a face. const std::string INPUT_IMAGE_NAME("lena.bmp"); cv::Mat input_image = cv::imread(INPUT_IMAGE_NAME); if(input_image.empty()) { std::cerr << "Failed to load" << INPUT_IMAGE_NAME << std::endl; return -1; } // Convert the image to grayscale and equalize the histogram. cv::Mat image_gray; cv::cvtColor(input_image, image_gray, CV_BGR2GRAY); cv::equalizeHist(image_gray, image_gray); // Attempt to detect one or more faces. std::vector<cv::Rect> faces; face_cascade.detectMultiScale(image_gray, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE, cv::Size(30, 30)); // Iterate over the detected faces and surround each one with an ellipse. std::for_each(faces.begin(), faces.end(), [&input_image](const cv::Rect& face_rect) { cv::Point center(face_rect.x + static_cast<int>(face_rect.width*0.5f), face_rect.y + static_cast<int>(face_rect.height*0.5f)); cv::ellipse(input_image, center, cv::Size(static_cast<int>(face_rect.width*0.5f), static_cast<int>(face_rect.height*0.5f)), 0, 0, 360, cv::Scalar(0, 0, 255), 4, 8, 0); }); cv::imshow("Face Detector", input_image); // Delay termination until some key is pressed. We want to give the user time to view the output. cv::waitKey(); return 0; }
11mseegjanjua-1
Main.cpp
C++
mit
2,285
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package MyDatabase; import java.io.Serializable; import java.util.ArrayList; import java.util.Vector; /** * * @author HUYNHLOC */ public class Data implements Serializable { Vector<Database> _databases; public Data() { _databases = new Vector<Database>(); } public Database getDatabase(String name) { for (int i = 0; i < _databases.size(); i++) { if (_databases.elementAt(i).getName().equals(name)) { return (Database) _databases.elementAt(i); } } return null; } public ArrayList getAllNameDatabases(){ ArrayList list = new ArrayList<String>(); for(int i=0;i<_databases.size();i++){ list.add(_databases.elementAt(i).getName()); } return list; } public boolean addDatabase(Database database) { for (int i = 0; i < _databases.size(); i++) { if (_databases.elementAt(i).getName().equals(database.getName())) { return false; } } _databases.add(database); return true; } public boolean deleteDatabase(String namedatabase) { for (int i = 0; i < _databases.size(); i++) { if (_databases.elementAt(i).getName().equals(namedatabase)) { _databases.remove(i); return true; } } return false; } public void show() { for (int i = 0; i < _databases.size(); i++) { _databases.elementAt(i).showDatabase(); } } }
121212-doancuoiky
trunk/Do An Final/Source Code/MyLibrary/src/MyDatabase/Data.java
Java
oos
1,752
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package MyDatabase; import java.io.Serializable; /** * * @author HUYNHLOC */ public class Command implements Serializable { public static enum CommandType { Message, // mot thong bao Query, // cau truy van TableData, // du lieu bang ValueData, // du lieu gia tri Login, LoginFail, LoginSuccess, ListNameDatabase, } private CommandType _cmdType; private String _UserSender; private String _Message; private Table _TableData; public Command(CommandType cmdtype, String message) { _cmdType = cmdtype; _Message = message; } public Command(CommandType cmdtype, Table tabledata) { _cmdType = cmdtype; _TableData = tabledata; } /** * @return the _cmdType */ public CommandType getCmdType() { return _cmdType; } /** * @param cmdType the _cmdType to set */ public void setCmdType(CommandType cmdType) { this._cmdType = cmdType; } /** * @return the _UserSender */ public String getUserSender() { return _UserSender; } /** * @param UserSender the _UserSender to set */ public void setUserSender(String UserSender) { this._UserSender = UserSender; } /** * @return the Message */ public String getMessage() { return _Message; } /** * @param Message the Message to set */ public void setMessage(String Message) { this._Message = Message; } /** * @return the _TableData */ public Table getTableData() { return _TableData; } /** * @param TableData the _TableData to set */ public void setTableData(Table TableData) { this._TableData = TableData; } }
121212-doancuoiky
trunk/Do An Final/Source Code/MyLibrary/src/MyDatabase/Command.java
Java
oos
2,030
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package MyDatabase; import java.io.*; /** * * @author HUYNHLOC */ public class Server_Data { //Seriable một đối tượng xuống file public static void SerialDatabase(String fileName, Data data) throws FileNotFoundException, IOException { //Tạo luồng ghi file FileOutputStream fos = new FileOutputStream(fileName); //Tạo luồng để seriable đối tượng ObjectOutputStream oos = new ObjectOutputStream(fos); //Chuyển tải đối tượng tới tập tin oos.writeObject(data); oos.flush(); fos.close(); oos.close(); } //Deseriable một đối tượng đã được seriable trước đó public static Data Deseriable(String fileName) throws FileNotFoundException, IOException, ClassNotFoundException { Data result = null; //Tạo luồng đọc file đã được seriable FileInputStream fis = new FileInputStream(fileName); //Tạo luồng để deseriable đối tượng ObjectInputStream ois= new ObjectInputStream(new BufferedInputStream(fis)); //Tiến hành khôi phục đối tượng result = ((Data)ois.readObject()); ois.close(); fis.close(); return result; } }
121212-doancuoiky
trunk/Do An Final/Source Code/MyLibrary/src/MyDatabase/Server_Data.java
Java
oos
1,511
package MyDatabase; import java.io.Serializable; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Sunlang */ public class Column implements Serializable{ String _nameCol; String _nameRefCol; Table _tableRef; int _type; boolean _boolPrimaryKey; boolean _boolForeignKey; public Column() { this("", "", null, 0, false, false); } public Column(String nameCol, String nameRefCol, Table tableRef, int type, boolean primaryKey, boolean foreignKey) { this._nameCol = nameCol.trim().toUpperCase(); if(_nameRefCol != null) this._nameRefCol = nameRefCol.trim().toUpperCase(); else this._nameRefCol = nameRefCol; this._tableRef = tableRef; this._type = type; this._boolPrimaryKey = primaryKey; this._boolForeignKey = foreignKey; } public String getNameCol() { return _nameCol; } public String getNameRefCol() { return _nameRefCol; } public Table getTableRef() { return _tableRef; } public int getType() { return _type; } public boolean isPrimaryKey() { return _boolPrimaryKey; } public boolean isForeignKey() { return _boolForeignKey; } }
121212-doancuoiky
trunk/Do An Final/Source Code/MyLibrary/src/MyDatabase/Column.java
Java
oos
1,488
package MyDatabase; import java.io.Serializable; import java.util.ArrayList; import java.util.Vector; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Sunlang */ public class Database implements Serializable{ private String _name; Vector<Table> _tables; public Database(String name) { _name = name; _tables = new Vector<Table>(); } public ArrayList getAllNameTable(){ ArrayList listname = new ArrayList(); for(int i=0;i<_tables.size();i++){ listname.add(_tables.elementAt(i).getNameTable()); } return listname; } public boolean addTable(Table table) { for(int i = 0; i<_tables.size(); i++) { if(_tables.elementAt(i).getNameTable().compareTo(table.getNameTable()) == 0) { return false; } } _tables.add(table); return true; } public Table getTable(String nameTable) { for(int i = 0; i<_tables.size(); i++) { if(_tables.elementAt(i).getNameTable().compareTo(nameTable) == 0) { return _tables.elementAt(i); } } return null; } public void showDatabase() { for(int i = 0; i<_tables.size(); i++) { _tables.elementAt(i).showTable(); } } /** * @return the _name */ public String getName() { return _name; } /** * @param name the _name to set */ public void setName(String name) { this._name = name; } //tich hop 12/6 //lay ten bang theo chi so //chua kiem tra i nhap vao co trong gioi han hay khong public Table GetTable(int i) { Table result; result= _tables.get(i); return result; } public int getSizeDatabase() { return _tables.size(); } }
121212-doancuoiky
trunk/Do An Final/Source Code/MyLibrary/src/MyDatabase/Database.java
Java
oos
2,118
package MyDatabase; import java.io.Serializable; import java.util.Vector; /* * To change this template, choose Tools | Templates and open the template in * the editor. */ /** * * @author Sunlang */ public class Table implements Serializable { String _nameTable; Vector<Column> _columns; Vector<Vector<Object>> _rows; public Table(String nameTable) { this._nameTable = nameTable.trim().toUpperCase(); this._columns = new Vector<Column>(); this._rows = new Vector<Vector<Object>>(); } public String getNameTable() { return this._nameTable; } public void setNameTable(String nameTable) { this._nameTable = nameTable; } public Vector<Column> getColumns() { return this._columns; } public void setColumns(Vector<Column> columns) { this._columns = columns; } public Vector<Vector<Object>> getRows() { return this._rows; } public void setRows(Vector<Vector<Object>> rows) { this._rows = rows; } public Column getPrimaryKeyCol() { for (int i = 0; i < this._columns.size(); i++) { if (this._columns.elementAt(i).isPrimaryKey()) { return _columns.elementAt(i); } } return null; } public Vector<Column> getForeignKeyCols() { Vector<Column> foreignKeyCols = new Vector<Column>(); for (int i = 0; i < this._columns.size(); i++) { if (this._columns.elementAt(i).isForeignKey()) { foreignKeyCols.add(_columns.elementAt(i)); } } return foreignKeyCols; } public int getIndexColumn(String nameCol) { for (int i = 0; i < _columns.size(); i++) { if (_columns.elementAt(i).getNameCol().equals(nameCol)) { return i; } } return -1; } public int getTypeCol(int index) { return this._columns.elementAt(index).getType(); } public String getNameCol(int index) { return this._columns.elementAt(index).getNameCol(); } public boolean isPrimaryKeyCol(int index) { return this._columns.elementAt(index).isPrimaryKey(); } public boolean isForeignKeyCol(int index) { return this._columns.elementAt(index).isForeignKey(); } public String getNameRefCol(int index) { return this._columns.elementAt(index).getNameRefCol(); } public Table getTableRef(int index) { return this._columns.elementAt(index).getTableRef(); } public boolean addColumn(String nameCol, String nameRefCol, Table tableRef, int type, boolean boolPrimaryKey, boolean boolForeignKey) { if (boolForeignKey) { int indexRefCol = tableRef.getIndexColumn(nameRefCol); if (indexRefCol == -1) { return false; } if (!tableRef.getColumns().elementAt(indexRefCol).isPrimaryKey()) { return false; } } Column tempCol = new Column(nameCol, nameRefCol, tableRef, type, boolPrimaryKey, boolForeignKey); this._columns.add(tempCol); return true; } //Trả về Table với các column được chọn, so sánh giá trị column tên colChoose của Object public Table getTableWithNameCols(Vector<String> nameCols, String colChoose, Object value) { Table result = new Table("New_Table"); //Nếu chọn tất cả các Column if (nameCols == null || nameCols.isEmpty()) { result.setColumns(this._columns); } else { for (int i = 0; i < nameCols.size(); i++) { //Chỉ add các cột nào được chọn thôi //EXCEPTION:SANG result.getColumns().add(this._columns.elementAt( this.getIndexColumn(nameCols.elementAt(i)))); } } //Nếu chọn tất cả các dòng if (value == null) { for (int i = 0; i < this._rows.size(); i++) { Vector<Object> tempRow = new Vector<Object>(); for (int j = 0; j < result.getColumns().size(); j++) { tempRow.add(this._rows.elementAt(i).elementAt( this.getIndexColumn(result.getColumns().elementAt(j).getNameCol()))); } result.getRows().add(tempRow); } } else { int indexColChoose = this.getIndexColumn(colChoose); int typeColChoose = this._columns.elementAt(indexColChoose)._type; for (int i = 0; i < this._rows.size(); i++) { if (typeColChoose == 0) { if (Integer.parseInt(this._rows.elementAt(i).elementAt(indexColChoose).toString()) == Integer.parseInt(value.toString())) { Vector<Object> tempRow = new Vector<Object>(); for (int j = 0; j < result.getColumns().size(); j++) { tempRow.add(this._rows.elementAt(i).elementAt( this.getIndexColumn(result.getColumns().elementAt(j).getNameCol()))); } result.getRows().add(tempRow); } } else { if (this._rows.elementAt(i).elementAt(indexColChoose).toString().equals(value.toString())) { Vector<Object> tempRow = new Vector<Object>(); for (int j = 0; j < result.getColumns().size(); j++) { tempRow.add(this._rows.elementAt(i).elementAt( this.getIndexColumn(result.getColumns().elementAt(j).getNameCol()))); } result.getRows().add(tempRow); } } } } return result; } public boolean deleteAllRow() { this._rows.clear(); return true; } //CHi moi xu ly truong hop a=b public boolean DeleteWithCondition(String Column, String Condition, String Value) { int indexColName = this.getIndexColumn(Column.trim()); if (indexColName == -1) { return false; } String strValue = Value.trim().toString(); for (int i = 0; i < this._rows.size(); i++) { String str = this._rows.elementAt(i).elementAt(indexColName).toString(); if (str.compareTo(strValue) == 0) { this._rows.removeElementAt(i); } } return true; } // Bo ngoac kep tra ra chuoi public String getStringValid(String str){ String temp = ""; if(str.contains("\"") ) temp = "\""; if(str.contains("\'")) temp = "'"; int indexdaunhaybatdau = str.indexOf(temp); if(indexdaunhaybatdau == -1 || indexdaunhaybatdau > 0) return ""; int count = str.length(); int indexdaunhayketthuc = str.lastIndexOf(temp); if(indexdaunhayketthuc != count -1) return ""; return str.substring(indexdaunhaybatdau+1, indexdaunhayketthuc); } public boolean DeleteWithConditionAndOr(String[] column, String[] condition, String[] Value, String DieuKien) { if (DieuKien.trim().equals("AND")) { int indexColName1 = this.getIndexColumn(column[0].trim()); if (indexColName1 == -1) { return false; } int indexColName2 = this.getIndexColumn(column[1].trim()); if (indexColName2 == -1) { return false; } //cho nay xu ly kieu du lieu la chuoi thoi String strValue1 = getStringValid(Value[0]).trim().toString(); String strValue2 = getStringValid(Value[1]).trim().toString(); for (int i = 0; i < this._rows.size(); i++) { String str1 = this._rows.elementAt(i).elementAt(indexColName1).toString(); String str2 = this._rows.elementAt(i).elementAt(indexColName2).toString(); if ((str1.compareTo(strValue1) == 0)&&(str2.compareTo(strValue2) == 0)) { this._rows.removeElementAt(i); } } return true; } if (DieuKien.trim().equals("OR")) { if (DeleteWithCondition(column[0], condition[0], Value[0]) && DeleteWithCondition(column[1], condition[1], Value[1])) { return true; } } return false; } //lấy tên hàm tham chiếu public String GetTableReferent() { String result = null; for (int i = 0; i < _columns.size(); i++) { if (_columns.elementAt(i).getTableRef() != null) { return _columns.elementAt(i).getTableRef().getNameTable(); } } return result; } public boolean updateValue(Vector<String> nameColsUpdate, Vector<Object> valuesUpdate, String namCol, Object value, String nameCol2, Object value2) { if (nameCol2 == null) { int indexColName = this.getIndexColumn(namCol); //Trường hợp nameCol và value là null if (indexColName == -1) { //return false; for (int i = 0; i < this._rows.size(); i++) { for (int j = 0; j < nameColsUpdate.size(); j++) { this._rows.elementAt(i).setElementAt( valuesUpdate.elementAt(j), this.getIndexColumn(nameColsUpdate.elementAt(j))); } } return true; } String strValue = value.toString(); for (int i = 0; i < this._rows.size(); i++) { String str = this._rows.elementAt(i).elementAt(indexColName).toString(); if (str.compareTo(strValue) == 0) { for (int j = 0; j < nameColsUpdate.size(); j++) { if (this.getIndexColumn(nameColsUpdate.elementAt(j)) == -1) { return false; } } for (int j = 0; j < nameColsUpdate.size(); j++) { this._rows.elementAt(i).setElementAt( valuesUpdate.elementAt(j), this.getIndexColumn(nameColsUpdate.elementAt(j))); } } } } //Trường hợp where ở update có 2 điều kiện (AND_OR) else { int indexColName = this.getIndexColumn(namCol); int indexColName2 = this.getIndexColumn(nameCol2); String strValue = value.toString(); String strValue2 = value2.toString(); for (int i = 0; i < this._rows.size(); i++) { String str = this._rows.elementAt(i).elementAt(indexColName).toString().toUpperCase().trim(); String str2 = this._rows.elementAt(i).elementAt(indexColName2).toString().toUpperCase().trim(); if (str.compareTo(strValue) == 0 && str2.compareTo(strValue2) == 0) { for (int j = 0; j < nameColsUpdate.size(); j++) { if (this.getIndexColumn(nameColsUpdate.elementAt(j)) == -1) { return false; } } for (int j = 0; j < nameColsUpdate.size(); j++) { this._rows.elementAt(i).setElementAt( valuesUpdate.elementAt(j), this.getIndexColumn(nameColsUpdate.elementAt(j))); } } } } return true; } public boolean deleteColumn(String nameCol, Object value) { int indexColName = this.getIndexColumn(nameCol); if (indexColName == -1) { return false; } String strValue = value.toString(); for (int i = 0; i < this._rows.size(); i++) { String str = this._rows.elementAt(i).elementAt(indexColName).toString(); if (str.compareTo(strValue) == 0) { this._rows.removeElementAt(i); } } return true; } public void showTable() { System.out.println("Ten Bang: " + this._nameTable); for (int iCol = 0; iCol < this._columns.size(); iCol++) { System.out.print(this.getNameCol(iCol) + "(Type: " + this._columns.elementAt(iCol).getType() + ")" + " "); } System.out.println(); System.out.println(); for (int i = 0; i < this._rows.size(); i++) { for (int j = 0; j < this._columns.size(); j++) { System.out.print(this._rows.elementAt(i).elementAt(j).toString() + " "); } System.out.println(); } } public boolean addRow(Vector<Object> row) { for (int i = 0; i < this._columns.size(); i++) { //Type của column hiện tại int typeCurrentCol = this._columns.elementAt(i).getType(); //Nếu column đó là thuộc tính khóa chính if (this._columns.elementAt(i).isPrimaryKey()) { //Nếu thuộc tính khóa chính của row là null if (row.elementAt(i) == null) { return false; } String primaryKeyInput = row.elementAt(i).toString(); for (int j = 0; j < this._rows.size(); j++) { if (this._rows.elementAt(j).elementAt(i).toString().equals(primaryKeyInput)) { return false; } } } //Nếu column đó là thuộc tính khóa ngoại if (this._columns.elementAt(i).isForeignKey()) { Column foreignCol = this._columns.elementAt(i); //tableRef = Table mà thuộc tính khóa ngoại này tham chiếu tới Table tableRef = foreignCol.getTableRef(); int index = tableRef.getIndexColumn(foreignCol.getNameRefCol()); //Nếu 2 thuộc tính này khác type if (typeCurrentCol != tableRef.getColumns().elementAt(index).getType()) { return false; } else { String foreignKeyInput = row.elementAt(i).toString().toUpperCase(); for (int j = 0; j < tableRef.getRows().size(); j++) { //Nếu tồn tại foreignKey này bên bảng mà nó tham chiếu if (tableRef.getRows().elementAt(j).elementAt(index).toString().toUpperCase().equals(foreignKeyInput)) { break; } else { if (j == tableRef.getRows().size() - 1) { return false; } } } } } } _rows.add(row); return true; } public Table joinTable(Table table2, String nameCol1, String nameCol2) { Table result = new Table("Table_JOIN"); Vector<Column> columnsTable2 = table2.getColumns(); Vector<Vector<Object>> rowsTable2 = table2.getRows(); int indexNameCol1 = getIndexColumn(nameCol1); int indexNameCol2 = table2.getIndexColumn(nameCol2); int typeNameCol1 = _columns.elementAt(indexNameCol1).getType(); int typeNameCol2 = columnsTable2.elementAt(indexNameCol2).getType(); if (typeNameCol1 != typeNameCol2) { return null; } for (int i = 0; i < _columns.size(); i++) { result._columns.add(_columns.elementAt(i)); } for (int i = 0; i < columnsTable2.size(); i++) { result._columns.add(columnsTable2.elementAt(i)); } for (int i = 0; i < _rows.size(); i++) { String valueNameCol1 = _rows.elementAt(i).elementAt(indexNameCol1).toString(); for (int j = 0; j < rowsTable2.size(); j++) { String valueNameCol2 = rowsTable2.elementAt(j).elementAt(indexNameCol2).toString(); if (valueNameCol1.compareTo(valueNameCol2) == 0) { Vector<Object> tempRow = new Vector<Object>(); for (int k = 0; k < _columns.size(); k++) { tempRow.add(_rows.elementAt(i).elementAt(k)); } for (int k = 0; k < columnsTable2.size(); k++) { tempRow.add(rowsTable2.elementAt(j).elementAt(k)); } result._rows.add(tempRow); } } } return result; } }
121212-doancuoiky
trunk/Do An Final/Source Code/MyLibrary/src/MyDatabase/Table.java
Java
oos
17,508
package client; import java.net.Socket; import MyDatabase.*; interface LoginWindowConnectListener{ public void handleConnectSusscess(Socket socket); } interface CommandListener{ public void handleReceiveCommand(Command cmd); }
121212-doancuoiky
trunk/Do An Final/Source Code/Client/src/client/Interface.java
Java
oos
246
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package client; /** * * @author HUYNHLOC */ public class TableResult extends javax.swing.JFrame { /** * Creates new form TableResult */ public TableResult() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(jTable1); jLabel1.setText("Table result"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(35, 35, 35) .addComponent(jLabel1) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(93, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; // End of variables declaration//GEN-END:variables }
121212-doancuoiky
trunk/Do An Final/Source Code/Client/src/client/TableResult.java
Java
oos
2,947
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package client; import javax.swing.table.DefaultTableModel; /** * * @author HUYNHLOC */ public class TableValues extends DefaultTableModel{ TableValues(String[] colNames, int i) { super(colNames, i); } @Override public boolean isCellEditable(int row, int column) { return false; } }
121212-doancuoiky
trunk/Do An Final/Source Code/Client/src/client/TableValues.java
Java
oos
457
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package client; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger; import MyDatabase.*; import java.io.*; /** * * @author HUYNHLOC */ public class ClientThread extends Thread { CommandListener _commandListener; private Socket _socket; private ObjectInputStream ois; private ObjectOutputStream oos; public ClientThread(Socket socket) { try { _socket = socket; oos = new ObjectOutputStream(new BufferedOutputStream(_socket.getOutputStream())); oos.flush(); ois = new ObjectInputStream(new BufferedInputStream(_socket.getInputStream())); } catch (IOException ex) { Logger.getLogger(ClientThread.class.getName()).log(Level.SEVERE, null, ex); } } // set nguoi lang nghe su kien public void SetCommandListener(CommandListener cmdlistener) { _commandListener = cmdlistener; } // day su kien nhan 1 command ra ngoai public void fireReceiveCommandEvent(Command cmd) { _commandListener.handleReceiveCommand(cmd); } synchronized public void SendCommand(Command cmd) { SendCommandToServer Sender = new SendCommandToServer(cmd); Sender.start(); } class SendCommandToServer extends Thread { private Command _cmdSend; public SendCommandToServer(Command cmd) { _cmdSend = cmd; } public void run() { try { oos.writeObject(_cmdSend); oos.flush(); } catch (IOException ex) { //Logger.getLogger(ClientThread.class.getName()).log(Level.SEVERE, null, ex); } this.interrupt(); System.gc(); } } public void run() { while (_socket.isConnected()) { try { Command cmdrec = (Command) ois.readObject(); fireReceiveCommandEvent(cmdrec); } catch (Exception ex) { //ex.printStackTrace(); break; } } Disconnect(); } public void Disconnect() { if (_socket != null && _socket.isConnected()) { try { ois.close(); oos.close(); _socket.shutdownInput(); _socket.shutdownOutput(); _socket.close(); _socket = null; } catch (IOException ex) { //Logger.getLogger(ClientThread.class.getName()).log(Level.SEVERE, null, ex); } } } }
121212-doancuoiky
trunk/Do An Final/Source Code/Client/src/client/ClientThread.java
Java
oos
2,952
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package client; import MyDatabase.Column; import MyDatabase.Command; import MyDatabase.Table; import java.lang.reflect.InvocationTargetException; import java.net.Socket; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.*; import javax.swing.plaf.basic.BasicInternalFrameTitlePane; /** * * @author HUYNHLOC */ public class MainWindow extends javax.swing.JFrame { // socket giao tiếp với server(nhan duoc tu loginwindow) private LoginWindow loginWindow; private ClientThread _client; private Socket _socket; private TableValues model; /** * Creates new form MainWindow */ public MainWindow() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); jTextArea_query = new javax.swing.JTextArea(); jButton_query = new javax.swing.JButton(); jComboBox1 = new javax.swing.JComboBox(); jLabel1 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jTable_main = new javax.swing.JTable(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); addWindowListener(new java.awt.event.WindowAdapter() { public void windowActivated(java.awt.event.WindowEvent evt) { formWindowActivated(evt); } public void windowOpened(java.awt.event.WindowEvent evt) { formWindowOpened(evt); } }); jPanel1.setBackground(java.awt.SystemColor.activeCaption); jTextArea_query.setColumns(20); jTextArea_query.setRows(5); jScrollPane2.setViewportView(jTextArea_query); jButton_query.setText("query"); jButton_query.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_queryActionPerformed(evt); } }); jComboBox1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox1ActionPerformed(evt); } }); jLabel1.setText("List Database"); jTable_main.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jTable_main.setName(""); jScrollPane1.setViewportView(jTable_main); jLabel2.setText("Table Result :"); jLabel3.setText("Type Query: "); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 318, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2) .addComponent(jLabel3)) .addGap(25, 25, 25) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton_query, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 509, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(33, 33, 33) .addComponent(jButton_query)) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened // TODO add your handling code here: _client = new ClientThread((_socket)); _client.SetCommandListener(new ReceiveCommandListener()); _client.start(); }//GEN-LAST:event_formWindowOpened private void jButton_queryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_queryActionPerformed // TODO add your handling code here: String query = jTextArea_query.getText().trim(); if (query.equals("")) { JOptionPane.showMessageDialog(MainWindow.this, "nhap cau quey", "Thong bao", 1); } else { query += "/" + (String) jComboBox1.getSelectedItem(); Command cmdQuery = new Command(Command.CommandType.Query, query); try { _client.SendCommand(cmdQuery); } catch (Exception e) { JOptionPane.showMessageDialog(MainWindow.this, "Loi ket noi", "Loi", 1); } } }//GEN-LAST:event_jButton_queryActionPerformed private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated // TODO add your handling code here: }//GEN-LAST:event_formWindowActivated private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jComboBox1ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton_query; private javax.swing.JComboBox jComboBox1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTable jTable_main; private javax.swing.JTextArea jTextArea_query; // End of variables declaration//GEN-END:variables /** * @param loginWindow the loginWindow to set */ public void setLoginWindow(LoginWindow loginWindow) { this.loginWindow = loginWindow; loginWindow.SetConnectListener(new LoginConnectSusscessListener()); } class LoginConnectSusscessListener implements LoginWindowConnectListener { @Override public void handleConnectSusscess(Socket socket) { _socket = socket; //JOptionPane.showMessageDialog(MainWindow.this, "Da nhan duoc socket " + _socket.getPort(), "thong bao", 1); loginWindow.dispose(); //_client.start(); } } // su ly cac command nhan duoc class ReceiveCommandListener implements CommandListener { @Override public void handleReceiveCommand(Command cmd) { Command.CommandType cmdType = (Command.CommandType) cmd.getCmdType(); switch (cmdType) { case Message: JOptionPane.showMessageDialog(MainWindow.this, cmd.getMessage(), "Thong bao", 1); break; // nhan duoc du lieu dang table case TableData: Table table = cmd.getTableData(); Vector colums = table.getColumns(); String[] colnames = new String[colums.size()]; for (int i = 0; i < colums.size(); i++) { colnames[i] = ((Column) colums.elementAt(i)).getNameCol(); } Vector rows = table.getRows(); model = new TableValues(colnames, 0); for (int i = 0; i < rows.size(); i++) { model.addRow((Vector) rows.elementAt(i)); } try { // set tablevalues SwingUtilities.invokeAndWait(SetTableValues); } catch (InterruptedException ex) { Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex); } catch (InvocationTargetException ex) { Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex); } break; // nhan gia tri case ValueData: break; // neu nhan duoc danh sach ten cac database case ListNameDatabase: jComboBox1.removeAll(); String[] list = cmd.getMessage().split(" "); for (int i = 0; i < list.length; i++) { jComboBox1.addItem(list[i]); } break; } } } // set TableValues cho table Runnable SetTableValues = new Runnable() { @Override public void run() { jTable_main.setModel(model); } }; }
121212-doancuoiky
trunk/Do An Final/Source Code/Client/src/client/MainWindow.java
Java
oos
12,411
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package client; import java.net.Inet4Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import javax.swing.JOptionPane; /** * * @author HUYNHLOC */ public class LoginWindow extends javax.swing.JFrame { // interface sử lý viec ket noi thanh cong hay that bai LoginWindowConnectListener connectListener; // socket det noi toi server Socket socket; /** * Creates new form LoginWindow */ public LoginWindow() { initComponents(); } public void SetConnectListener(LoginWindowConnectListener listener){ connectListener = listener; } public void fireConnectSusscessEvent(){ connectListener.handleConnectSusscess(socket); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jButton_connect = new javax.swing.JButton(); jTextField_port = new javax.swing.JTextField(); jTextField_serverip = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("LoginWindow"); setBackground(new java.awt.Color(0, 153, 255)); setResizable(false); jPanel1.setBackground(new java.awt.Color(153, 153, 255)); jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); jButton_connect.setText("Connect"); jButton_connect.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_connectActionPerformed(evt); } }); jTextField_port.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { jTextField_portKeyTyped(evt); } }); jTextField_serverip.setText("localhost"); jLabel2.setText("Port"); jLabel1.setText("SerIP"); jLabel3.setText("Nhập serverIp và Port :"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(25, 25, 25) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButton_connect) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel3) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTextField_serverip)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel2) .addGap(18, 18, 18) .addComponent(jTextField_port, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(19, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel3) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField_serverip, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField_port, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addGap(27, 27, 27) .addComponent(jButton_connect) .addGap(29, 29, 29)) ); jTextField_port.getAccessibleContext().setAccessibleName("txt_port"); jTextField_serverip.getAccessibleContext().setAccessibleName("txt_serverip"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton_connectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_connectActionPerformed // TODO add your handling code here: if(jTextField_serverip.getText().trim().equals("")||jTextField_port.getText().trim().equals("")){ JOptionPane.showMessageDialog(LoginWindow.this, "Thieu thong tin input", "Loi", 1); }else{ try{ socket = new Socket(jTextField_serverip.getText().trim(), Integer.parseInt(jTextField_port.getText().trim())); MainWindow mainWindow = new MainWindow(); mainWindow.setLoginWindow(this); mainWindow.setLocation(400, 200); mainWindow.setVisible(true); //JOptionPane.showMessageDialog(LoginWindow.this, "ket noi thanh cong", "thong bao", 1); fireConnectSusscessEvent(); }catch(Exception e){ //e.printStackTrace(); JOptionPane.showMessageDialog(LoginWindow.this, "Loi ket noi", "Loi", 1); } } }//GEN-LAST:event_jButton_connectActionPerformed private void jTextField_portKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField_portKeyTyped // TODO add your handling code here: Character c = evt.getKeyChar(); if(c>'9'|| c<'0'){ evt.consume(); } }//GEN-LAST:event_jTextField_portKeyTyped /** * @param args the command line arguments */ public static void main(String args[]) { /* * Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* * If Nimbus (introduced in Java SE 6) is not available, stay with the * default look and feel. For details see * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(LoginWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(LoginWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(LoginWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(LoginWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* * Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { LoginWindow loginWindow = new LoginWindow(); loginWindow.setLocation(400, 200); loginWindow.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton_connect; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; private javax.swing.JTextField jTextField_port; private javax.swing.JTextField jTextField_serverip; // End of variables declaration//GEN-END:variables }
121212-doancuoiky
trunk/Do An Final/Source Code/Client/src/client/LoginWindow.java
Java
oos
9,878
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package SQLParse; import MyDatabase.Database; import MyDatabase.Table; import MyQuery.Query_PhepToan; import MyQuery.String_Query; import java.util.Vector; /** * * @author HUYNHLOC */ public class SQLParser { String Query; String_Query QueryParser; String DKNhanDuoc; String ColumnNhanDuoc; String ValueNhanDuoc; String[] DSColumnNhanDuoc; String[] DSValueNhanDuoc; String[] DSDieuKienNhanDuoc; String[] DSColumn; String[] DSTable; String[] DSValue;//Them cho truong hop insert update private Table TableResult; //Ket qua tra ve cho truong hop select //Thêm vào ngày 11/6-SANG private int _soDKOWhere; private String _DKOWhere; // là AND hay là OR private Database _database; private int _queryLevels; public SQLParser() { QueryParser = new String_Query(); } public SQLParser(String query, Database database) { _database = database; Query = query; _soDKOWhere = QueryParser.getSoDKOWhere(); _queryLevels = QueryParser.getQueryLevels(); } public boolean SQLResult() { switch (QueryParser.GetConmmandQuery()) { case "SELECT": { Vector<String> vtColumns = new Vector<>(); DSColumn = QueryParser.getDsColumn(); if (DSColumn != null) { if (DSColumn.length <= 0) { TableResult = null; return false; } for (int iCol = 0; iCol < DSColumn.length; iCol++) { vtColumns.add(DSColumn[iCol]); } } //Danh sách bảng: trường hợp này chỉ dùng khi có kết 2 bảng //Thông thường thì DSTable chỉ có một bảng DSTable = QueryParser.getDsTable(); if (DSTable.length <= 0) { TableResult = null; return false; } else {// neu danh sac table truy van khong co trong database thi return false for (int i = 0; i < DSTable.length; i++) { if ((_database.getTable(DSTable[i])) == null) { return false; } } } if (_soDKOWhere == 0) { TableResult = _database.getTable(DSTable[0]).getTableWithNameCols(vtColumns, null, null); if (TableResult == null) { System.out.println("TableResult = null trong SQLParser.java"); return false; } return true; } if (_soDKOWhere == 1 && _queryLevels == 1 && !QueryParser.isKetBang()) { DKNhanDuoc = QueryParser.getDKNhanDuoc(); ColumnNhanDuoc = QueryParser.getColumnNhanDuoc(); ValueNhanDuoc = QueryParser.getValueNhanDuoc(); Query_PhepToan query = new Query_PhepToan(_database.getTable(DSTable[0]), ColumnNhanDuoc, ValueNhanDuoc); TableResult = query.ResultCap1(query.LayPhepToan(DKNhanDuoc)).getTableWithNameCols(vtColumns, null, null); if (TableResult == null) { System.out.println("TableResult = null trong SQLParser.java"); return false; } return true; } if (_soDKOWhere == 2 && DSTable.length == 1) { _DKOWhere = QueryParser.getDkOWhere(); DSColumnNhanDuoc = QueryParser.getDsColumnNhanDuoc(); DSValueNhanDuoc = QueryParser.getDsValueNhanDuoc(); DSDieuKienNhanDuoc = QueryParser.getDsDieuKienNhanDuoc(); Query_PhepToan query = new Query_PhepToan(_database.getTable(DSTable[0]), DSColumnNhanDuoc[0], DSValueNhanDuoc[0]); Table tableresult1 = query.ResultCap1(query.LayPhepToan(DSDieuKienNhanDuoc[0])); Query_PhepToan queryPhepToan2 = new Query_PhepToan(tableresult1, DSColumnNhanDuoc[1], DSValueNhanDuoc[1]); TableResult = queryPhepToan2.ResultCap1(queryPhepToan2.LayPhepToanCap1( DSDieuKienNhanDuoc[1])).getTableWithNameCols(vtColumns, null, null); if (TableResult == null) { System.out.println("TableResult = null trong SQLParser.java"); return false; } return true; } if (_soDKOWhere == 1 && _queryLevels == 2) { Table temp = QueryParser.getTableTempForLongCap(); DKNhanDuoc = QueryParser.getDKNhanDuoc(); Query_PhepToan query = new Query_PhepToan(_database.getTable(DSTable[0]), temp.getNameCol(0), null); String nameCol2 = temp.getNameCol(0); int iPhepToan = query.LayPhepToanCap2(DKNhanDuoc); Table result = query.ResultCap2(temp, nameCol2, iPhepToan); TableResult = result.getTableWithNameCols(vtColumns, null, null); if (TableResult == null) { System.out.println("TableResult = null trong SQLParser.java"); return false; } return true; } //Trường hợp kết đơn giản //select hocsinh.mssv, hocsinh.hoten, lophoc.giaovienchunhiem where hocsinh.ma_lop = lophoc.malop if (_soDKOWhere == 1 && QueryParser.isKetBang()) { DKNhanDuoc = QueryParser.getDKNhanDuoc(); ColumnNhanDuoc = QueryParser.getColumnNhanDuoc(); ValueNhanDuoc = QueryParser.getValueNhanDuoc(); //DSTable nhận được thì giữ nguyên //Danh sách cột thì kèm theo danh sách bảng với thứ tự đó nữa //Ví dụ câu trên thì DSColumn trả về là hocsinh.mssv + hocsinh.hoten + lophoc.giaovienchunhiem //ColumnNhanDuoc = hocsinh.ma_lop; //ValueNhanDuoc = lophoc.malop //Cần tách một cái là DScolumn = mssv + hoten + giaovienchunhiem if (DSColumn != null) { for (int iCol = 0; iCol < DSColumn.length; iCol++) { DSColumn[iCol] = DSColumn[iCol].split("\\.")[1]; } vtColumns = new Vector<>(); for (int iCol = 0; iCol < DSColumn.length; iCol++) { vtColumns.add(DSColumn[iCol]); } } //So sánh để lấy đúng bảng và cột so sánh //Ví dụ hocsinh thì ma_lop còn lophoc thì malop String colName1 = ""; String colName2 = ""; if (ColumnNhanDuoc.split("\\.")[0].compareTo(DSTable[0]) == 0) { colName1 = ColumnNhanDuoc.split("\\.")[1]; colName2 = ValueNhanDuoc.split("\\.")[1]; } else { colName2 = ColumnNhanDuoc.split("\\.")[1]; colName1 = ValueNhanDuoc.split("\\.")[1]; } Table result = _database.getTable(DSTable[0]).joinTable(_database.getTable(DSTable[1]), colName1, colName2); TableResult = result.getTableWithNameCols(vtColumns, null, null); return true; } } case "INSERT": { DSTable = QueryParser.getDsTable(); if (DSTable.length != 1) { return false; } DSValue = QueryParser.getDsValue(); Table table1 = _database.getTable(DSTable[0]); if (table1 == null) {//kiểm tra database có bảng hay không nếu không có thì return false return false; } Vector<Object> row = new Vector<>(); for (int i = 0; i < DSValue.length; i++) { row.add(Query_PhepToan.getStringValid(DSValue[i].trim().toUpperCase())); } if (!table1.addRow(row)) { System.out.println("table1 không addRow được trong SQLParser.java"); return false; } TableResult = table1; if (TableResult == null) { System.out.println("TableResult = null trong SQLParser.java"); return false; } return true; } case "UPDATE": { DSColumn = QueryParser.getDsColumn(); Vector<String> rowColumn = new Vector<String>(); for (int i = 0; i < DSColumn.length; i++) { rowColumn.add(DSColumn[i].trim().toUpperCase()); } DSValue = QueryParser.getDsValue(); Vector<Object> rowValue = new Vector<Object>(); for (int i = 0; i < DSValue.length; i++) { rowValue.add(Query_PhepToan.getStringValid(DSValue[i].trim().toUpperCase())); } Table temp = QueryParser.getTableUpdate(); boolean kq = false; if (QueryParser.getSoDKOWhere() == 0) { kq = temp.updateValue(rowColumn, rowValue, null, null, null, null); } if (QueryParser.getSoDKOWhere() == 1) { kq = temp.updateValue(rowColumn, rowValue, QueryParser.getColumnNhanDuoc(), Query_PhepToan.getStringValid(QueryParser.getValueNhanDuoc().trim().toUpperCase()), null, null); } if (QueryParser.getSoDKOWhere() == 2) { kq = temp.updateValue(rowColumn, rowValue, QueryParser.getDsColumnNhanDuoc()[0], Query_PhepToan.getStringValid(QueryParser.getDsValueNhanDuoc()[0]).trim().toUpperCase(), QueryParser.getDsColumnNhanDuoc()[1], Query_PhepToan.getStringValid(QueryParser.getDsValueNhanDuoc()[1]).trim().toUpperCase()); } TableResult = temp; if(TableResult == null) { System.out.println("TableResult = null trong SQLParser.java"); return false; } return kq; } //delete from sinhvien where mssv='0912389' //delete from sinhvien //delete from sinhvien where mssv='0912389' and ma_lop='Ma_Lop_01' case "DELETE": { _soDKOWhere = QueryParser.getSoDKOWhere(); DSTable = QueryParser.getDsTable(); if (DSTable.length != 1) { return false; } Table tabledelete = _database.getTable(DSTable[0]); if (tabledelete == null)//nếu không có table trong database { return false; } String tableReferent = LayBangThamChieu(tabledelete); if (_soDKOWhere == 0) {//nếu không có điều kiện where thì xóa hết if (tableReferent == null)//không bị tham chiếu từ bảng khác { if (tabledelete.deleteAllRow()) { return true; } return false; } else//nếu bị tham chiếu từ bảng khác thì không xóa { return false; } } if (_soDKOWhere == 1) { //xóa Bảng với điều kiện DKNhanDuoc = QueryParser.getDKNhanDuoc(); ValueNhanDuoc = Query_PhepToan.getStringValid(QueryParser.getValueNhanDuoc()); ColumnNhanDuoc = QueryParser.getColumnNhanDuoc(); //kiểm tra kết quả trả về của các giá trị có bằng null hay không if ((DKNhanDuoc == null) && (ValueNhanDuoc == null) && (ColumnNhanDuoc == null)) { return false; } if (tableReferent == null) { if (tabledelete.DeleteWithCondition(ColumnNhanDuoc, DKNhanDuoc, ValueNhanDuoc)) { System.out.println("Xoa truong hop 2 thanh cong"); TableResult = tabledelete; return true; } else { System.out.println("Xoa truong hop 2 that bai"); return false; } } else { return false;//co tham chieu tu bang khac //o day chua xu ly truong hop co tham chieu tu bang khac //nhung gia tri can xoa khong bi tham chieu } } if (_soDKOWhere == 2) { //xóa cot voi dieu kien DSColumnNhanDuoc = QueryParser.getDsColumnNhanDuoc(); DSDieuKienNhanDuoc = QueryParser.getDsDieuKienNhanDuoc(); DSValueNhanDuoc = QueryParser.getDsValueNhanDuoc(); //kết quả trả về quá phạm vi if ((DSColumnNhanDuoc.length != 2) && (DSDieuKienNhanDuoc.length != 2) && (DSValueNhanDuoc.length != 2)) { return false; } _DKOWhere = QueryParser.getDkOWhere(); //không lấy được loại điều kiện if (_DKOWhere == null) { return false; } if (tabledelete.DeleteWithConditionAndOr(DSColumnNhanDuoc, DSColumnNhanDuoc, DSValueNhanDuoc, _DKOWhere)) { TableResult = tabledelete; return true; } return false; } else { return false;//co tham chieu tu bang khac //o day chua xu ly truong hop co tham chieu tu bang khac //nhung gia tri can xoa khong bi tham chieu } } } return false; } public String LayNoiDung(String str) { int index = str.indexOf("\""); if (index == -1) { return str; } else { return str.substring(1, str.length() - 1); } } /** * @return the TableResult */ public Table getTableResult() { return TableResult; } public String GetQueryComment() { return QueryParser.GetConmmandQuery(); } //tham so table la table muon tim bang tham chieu //chi ho tro cho 1 bang tham chieu private String LayBangThamChieu(Table table) { String result = null; int DatabaseSize = _database.getSizeDatabase(); for (int i = 0; i < DatabaseSize; i++)// { //lay bang ten bang tham chieu cua bang dang xet if (_database.GetTable(i).GetTableReferent() != null) { if (_database.GetTable(i).GetTableReferent().equals(table.getNameTable())) { return _database.GetTable(i).getNameTable(); } } } return result; } //Set cau truy van va database hien tai //public void setQuery(String query, Database database) //ham tra ve kieu boolean public boolean setQuery(String query, Database database) { Query = query; _database = database; QueryParser.SetStrQuery(query); QueryParser.SetTrDatabase(database); //kiểm tra có parse được hay không if (QueryParser.Parse()) {//kiểm tra có truy vấn được hay không _soDKOWhere = QueryParser.getSoDKOWhere(); _queryLevels = QueryParser.getQueryLevels(); if (SQLResult()) { return true; } } return false; } // lay danh sac table duoc truy van public String[] getDStable() { return DSTable; } }
121212-doancuoiky
trunk/Do An Final/Source Code/Server/src/SQLParse/SQLParser.java
Java
oos
17,372
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package MyQuery; /** * * @author Sunlang */ //Where a = 3 and b >2 //Where a = 3 or b>2 public class WhereParse { private String _strDieuKienWhere; private String[] _dsColumnNhanDuoc; private String[] _dsValueNhanDuoc; private String[] _dsDieuKienNhanDuoc; private String AND_OR; public WhereParse(String strDieuKien) { _dsColumnNhanDuoc = new String[2]; _dsDieuKienNhanDuoc = new String[2]; _dsValueNhanDuoc = new String[2]; _strDieuKienWhere = strDieuKien.trim(); if(_strDieuKienWhere.contains("AND")){ AND_OR = "AND"; } else{ AND_OR = "OR"; } String[] temp = _strDieuKienWhere.split(AND_OR); String strDk1 = temp[0].trim(); String strDk2 = temp[1].trim(); _dsColumnNhanDuoc[0] = SeparateStrDieuKien(strDk1)[0]; _dsDieuKienNhanDuoc[0] = SeparateStrDieuKien(strDk1)[1]; _dsValueNhanDuoc[0] = SeparateStrDieuKien(strDk1)[2]; _dsColumnNhanDuoc[1] = SeparateStrDieuKien(strDk2)[0]; _dsDieuKienNhanDuoc[1] = SeparateStrDieuKien(strDk2)[1]; _dsValueNhanDuoc[1] = SeparateStrDieuKien(strDk2)[2]; } public String[] SeparateStrDieuKien(String strDK)//Trả về cột, phép toán, giá trị { //a>b String[] result = new String[3]; for (int i = 0; i < String_Query._dsDKKiemTra.length; i++) { if (strDK.contains(String_Query._dsDKKiemTra[i])) { result[1] = String_Query._dsDKKiemTra[i].trim(); //> result[0] = strDK.split(result[1])[0].trim();//a result[2] = strDK.split(result[1])[1].trim(); //b //break; Vì > và >= } } return result; } public String getDK() { return AND_OR; } public String[] getDSCotNhanDuoc() { return _dsColumnNhanDuoc; } public String[] getDSValueNhanDuoc() { return _dsValueNhanDuoc; } public String[] getDSDKNhanDuoc() { return _dsDieuKienNhanDuoc; } }
121212-doancuoiky
trunk/Do An Final/Source Code/Server/src/MyQuery/WhereParse.java
Java
oos
2,442
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package MyQuery; import MyDatabase.Column; import MyDatabase.Table; import java.util.Vector; /** * * @author Sunlang */ public class Query_PhepToan { Table _table; String _colName; Object _valueCol; String[] PhepToanCap1 = {"=", "!=", "<", "<=", ">", ">="}; String[] PhepToanCap2 = {"IN", "NOT IN", ">ALL", ">=ALL", "<ALL", "<=ALL"}; String[] PhepToan_All = {"=", "!=", "<", "<=", ">", ">=", "IN", "NOT IN", ">ALL", ">=ALL", "<ALL", "<=ALL"}; //int _iPhepToan; //Result Cấp 1: == : 0, !=: 1 , <: 2, <= 3, > 4, >= 5 //Result Cấp 2: IN: 0, NOT In :1, //Result Cấp 2: Lớn hơn so với tất cả: 2, Lớn hoặc bằng so với tất cả: 3 //Result Cấp 2: <All: 4, <=All 5 public Query_PhepToan(Table _table, String _colName, Object _valueCol) { this._table = _table; this._colName = _colName; this._valueCol = _valueCol; } public int LayPhepToanCap1(String str) { for (int i = 0; i < PhepToanCap1.length; i++) { if (PhepToanCap1[i].equals(str)) { return i; } } return -1; } public int LayPhepToanCap2(String str) { for (int i = 0; i < PhepToanCap1.length; i++) { if (PhepToanCap2[i].equals(str)) { return i; } } return -1; } public int LayPhepToan(String str) { for (int i = 0; i < PhepToan_All.length; i++) { if (PhepToan_All[i].equals(str)) { return i; } } return -1; } public Table ResultCap1(int _iPhepToan) { Table result = new Table("Table_Result"); int indexCol = _table.getIndexColumn(_colName); if (indexCol == -1) { return null; } for (int i = 0; i < _table.getColumns().size(); i++) { result.getColumns().add(_table.getColumns().elementAt(i)); } int typeCol = _table.getColumns().elementAt(indexCol).getType(); if (typeCol == 0) { int valueCol = Integer.parseInt(_valueCol.toString()); for (int i = 0; i < _table.getRows().size(); i++) { boolean boolCheck = false; int value = Integer.parseInt( _table.getRows().elementAt(i).elementAt(indexCol).toString()); Vector<Object> tempRow = new Vector<Object>(); switch (_iPhepToan) { case 0: if (valueCol == value) { boolCheck = true; } break; case 1: if (valueCol != value) { boolCheck = true; } break; case 2: if (valueCol > value) { boolCheck = true; } break; case 3: if (valueCol >= value) { boolCheck = true; } break; case 4: if (valueCol < value) { boolCheck = true; } break; case 5: if (valueCol <= value) { boolCheck = true; } break; } if (boolCheck) { for (int j = 0; j < _table.getColumns().size(); j++) { tempRow.add(_table.getRows().elementAt(i).elementAt(j)); } result.addRow(tempRow); } } } else { String valueCol = getStringValid(_valueCol.toString()).toUpperCase().trim(); if (valueCol.equals("")) { return null; } for (int i = 0; i < _table.getRows().size(); i++) { boolean boolCheck = false; String value = _table.getRows().elementAt(i).elementAt(indexCol).toString().toUpperCase().trim(); Vector<Object> tempRow = new Vector<Object>(); switch (_iPhepToan) { case 0: if (valueCol.compareTo(value) == 0) { boolCheck = true; } break; case 1: if (valueCol.compareTo(value) != 0) { boolCheck = true; } break; case 2: if (valueCol.compareTo(value) > 0) { boolCheck = true; } break; case 3: if (valueCol.compareTo(value) >= 0) { boolCheck = true; } break; case 4: if (valueCol.compareTo(value) < 0) { boolCheck = true; } break; case 5: if (valueCol.compareTo(value) <= 0) { boolCheck = true; } break; } if (boolCheck) { for (int j = 0; j < _table.getColumns().size(); j++) { tempRow.add(_table.getRows().elementAt(i).elementAt(j)); } result.addRow(tempRow); } } } return result; } // Bo ngoac kep tra ra chuoi public static String getStringValid(String str) { String temp = ""; if (str.contains("\"")) { temp = "\""; } if (str.contains("\'")) { temp = "'"; } int indexdaunhaybatdau = str.indexOf(temp); if (indexdaunhaybatdau == -1 || indexdaunhaybatdau > 0) { return str; } int count = str.length(); int indexdaunhayketthuc = str.lastIndexOf(temp); if (indexdaunhayketthuc != count - 1) { return str; } return str.substring(indexdaunhaybatdau + 1, indexdaunhayketthuc); } //Lồng cấp 2 //Select * from SINHVIEN where MSSV IN select Ma_so_sv from SV_CNTT //_table là SINHVIEN, _nameCol là MSSV //table2 là SV_CNTT, nameCol2 là Ma_so_sv //Ở đây ko sử dụng _valueCol; public Table ResultCap2(Table table2, String nameCol2, int _iPhepToan) { Table result = new Table("Result_Table"); Vector<Column> columnsTable1 = _table.getColumns(); Vector<Column> columnsTable2 = table2.getColumns(); Vector<Vector<Object>> rowsTable1 = _table.getRows(); Vector<Vector<Object>> rowsTable2 = table2.getRows(); int indexNameCol1 = _table.getIndexColumn(_colName); int indexNameCol2 = table2.getIndexColumn(nameCol2); int typeNameCol1 = columnsTable1.elementAt(indexNameCol1).getType(); int typeNameCol2 = columnsTable2.elementAt(indexNameCol2).getType(); if (typeNameCol1 != typeNameCol2) { return null; } if (indexNameCol1 == -1 || indexNameCol2 == -1) { return null; } for (int i = 0; i < columnsTable1.size(); i++) { result.getColumns().add(columnsTable1.elementAt(i)); } if (_iPhepToan == 0) { for (int i = 0; i < rowsTable1.size(); i++) { String valueCol1 = rowsTable1.elementAt(i).elementAt(indexNameCol1).toString(); for (int j = 0; j < rowsTable2.size(); j++) { String valueCol2 = rowsTable2.elementAt(j).elementAt(indexNameCol2).toString(); if (valueCol1.compareTo(valueCol2) == 0) { Vector<Object> tempRow = new Vector<Object>(); for (int k = 0; k < columnsTable1.size(); k++) { tempRow.add(rowsTable1.elementAt(i).elementAt(k)); } result.addRow(tempRow); break; } } } return result; } else { if (_iPhepToan == 1) { boolean boolCheck = true; for (int i = 0; i < rowsTable1.size(); i++) { String valueCol1 = rowsTable1.elementAt(i).elementAt(indexNameCol1).toString(); for (int j = 0; j < rowsTable2.size(); j++) { String valueCol2 = rowsTable2.elementAt(j).elementAt(indexNameCol2).toString(); if (valueCol1.compareTo(valueCol2) == 0) { boolCheck = false; break; } } if (boolCheck) { Vector<Object> tempRow = new Vector<Object>(); for (int j = 0; j < columnsTable1.size(); j++) { tempRow.add(rowsTable1.elementAt(i).elementAt(j)); } result.addRow(tempRow); } } } else { if (typeNameCol1 == 0) { boolean boolCheck = true; for (int i = 0; i < columnsTable1.size(); i++) { int valueCol1 = Integer.parseInt( rowsTable1.elementAt(i).elementAt(indexNameCol1).toString()); Vector<Object> tempRow = new Vector<Object>(); for (int j = 0; j < columnsTable2.size(); j++) { int valueCol2 = Integer.parseInt( rowsTable2.elementAt(j).elementAt(indexNameCol2).toString()); switch (_iPhepToan) { //Trường hợp thứ 2 case 2: if (valueCol1 <= valueCol2) { boolCheck = false; } break; case 3: if (valueCol1 < valueCol2) { boolCheck = false; } break; case 4: if (valueCol1 >= valueCol2) { boolCheck = false; } break; case 5: if (valueCol1 > valueCol2) { boolCheck = false; } break; } } if (boolCheck) { for (int j = 0; j < _table.getColumns().size(); j++) { tempRow.add(_table.getRows().elementAt(i).elementAt(j)); } result.addRow(tempRow); } } } else { boolean boolCheck = true; for (int i = 0; i < columnsTable1.size(); i++) { String valueCol1 = rowsTable1.elementAt(i).elementAt(indexNameCol1).toString(); Vector<Object> tempRow = new Vector<Object>(); for (int j = 0; j < columnsTable2.size(); j++) { String valueCol2 = rowsTable2.elementAt(j).elementAt(indexNameCol2).toString(); switch (_iPhepToan) { case 2: if (valueCol1.compareTo(valueCol2) <= 0) { boolCheck = false; } break; case 3: if (valueCol1.compareTo(valueCol2) < 0) { boolCheck = false; } break; case 4: if (valueCol1.compareTo(valueCol2) >= 0) { boolCheck = false; } break; case 5: if (valueCol1.compareTo(valueCol2) > 0) { boolCheck = false; } break; } } if (boolCheck) { for (int j = 0; j < _table.getColumns().size(); j++) { tempRow.add(_table.getRows().elementAt(i).elementAt(j)); } result.addRow(tempRow); } } } } return result; } } }
121212-doancuoiky
trunk/Do An Final/Source Code/Server/src/MyQuery/Query_PhepToan.java
Java
oos
14,167
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package MyQuery; import MyDatabase.Database; import MyDatabase.Table; import java.util.Vector; /** * * @author Sunlang */ //Trường hợp //SELECT MSSV FROM SINHVIEN WHERE MSSV (In, Not In, >All, >=All, <All, <=All) //(SELECT Ma_so FROM table2 WHERE Colum =, > .... value)<-- //CHỈ CẦN TRẢ VỀ TÊN BẢNG VÀ TÊN CỘT RỒI SỦ DỤNG String_PhepToan.ResultCap2 o ben ngoai public class WhereParse_HaveSelect { private Database _database; private String _strDKWhereHaveSelect; private String _strKhongCoWhereThuNhat; private String _columnNameOWhere; private Table _tableReturnHaveColumnName; public WhereParse_HaveSelect(String strDKWhereHaveSelect, Database database) { _database = database; _strDKWhereHaveSelect = strDKWhereHaveSelect.trim().toUpperCase(); //TableReturnHaveColumnFromSelect(); } public void ExecuteTableReturnHaveColumnFromSelect() { boolean isWhereThu2 = true; int indexSelect = _strDKWhereHaveSelect.indexOf("SELECT"); _strKhongCoWhereThuNhat = _strDKWhereHaveSelect.substring( indexSelect, _strDKWhereHaveSelect.length()-1).trim();//-1 bỏ dấu ) indexSelect = 0; int indexFrom = _strKhongCoWhereThuNhat.indexOf("FROM"); int indexWhere = _strKhongCoWhereThuNhat.indexOf("WHERE"); if (indexWhere == -1) { isWhereThu2 = false; indexWhere = _strKhongCoWhereThuNhat.length(); } _columnNameOWhere = _strKhongCoWhereThuNhat.substring(indexSelect + 6, indexFrom).trim(); _tableReturnHaveColumnName = new Table("Table_" + _columnNameOWhere); String nameTableSauWhere = _strKhongCoWhereThuNhat.substring(indexFrom + 4, indexWhere).trim(); Vector<String> nameCols = new Vector<>(); nameCols.add(_columnNameOWhere); if (!isWhereThu2) { _tableReturnHaveColumnName = _database.getTable(nameTableSauWhere).getTableWithNameCols(nameCols, null, null); } else { String strDieuKien = _strKhongCoWhereThuNhat.substring( indexWhere + 5, _strKhongCoWhereThuNhat.length()).trim(); String dieukien = null; String cot = null; String giatri = null; for (int i = 0; i < String_Query._dsDKKiemTra.length; i++) { if (strDieuKien.contains(String_Query._dsDKKiemTra[i])) { dieukien = String_Query._dsDKKiemTra[i]; cot = strDieuKien.split(dieukien)[0].trim(); giatri = strDieuKien.split(dieukien)[1].trim(); //break; Vì > và >= } } Query_PhepToan query1 = new Query_PhepToan( _database.getTable(nameTableSauWhere), cot, (Object) giatri); _tableReturnHaveColumnName = query1.ResultCap1(query1.LayPhepToan(dieukien)); } } public Table getTable() { return _tableReturnHaveColumnName; } public String getNameCol() { return _columnNameOWhere; } }
121212-doancuoiky
trunk/Do An Final/Source Code/Server/src/MyQuery/WhereParse_HaveSelect.java
Java
oos
3,291
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package MyQuery; import MyDatabase.Database; import MyDatabase.Table; /** * * @author Sunlang */ public class String_Query { String _strQuery; String _commandQuery; int _queryLevels; static String[] _dsDKKiemTra = {"=", "!=", "<", "<=", ">", ">=", " IN ", "NOT IN", ">ALL", ">=ALL", "<ALL", "<=ALL"}; static String[] _dsDKKiemTra2 = {"=", "!=", "<", "<=", ">"};//thêm vô cho xử lý trường hợp delete tránh bị lỗi //nếu cột hay tên có kí từ in thì sẽ bị lỗi private String _DKNhanDuoc; private String _ColumnNhanDuoc; private String _valueNhanDuoc; private String[] _dsColumnNhanDuoc; private String[] _dsValueNhanDuoc; private String[] _dsDieuKienNhanDuoc; private String _dkOWhere; private String[] _dsColumn; private String[] _dsTable; //luan danh sach value dung cho ham insert update private String[] _dsValue; //Bảng chỉ trả về cho trường hợp update private Table _tableUpdate; //Thêm vào ngày 11/6 - Sang private int _soDKOWhere; //Nếu _dkOWhwere != null (= AND_OR) thì soDKOWhere = 2 //Nếu _dkOWhere == null, tức là chỉ có 1 điều kiện thì soDKWhere bằng 1; //Mếu không có _dkOWhere thì _soDKOwhere = 0; private Database _database; private Table _tempTableForLongCap; private boolean _isKetBang = false;//Trường hợp kết bảng hay không, chỉ sử dụng 1 lần ở select public String_Query() { _strQuery = ""; } //Neu xu ly co loi trong xulylenh() public boolean Parse() { //Chuẩn hóa chuỗi và xem chuỗi query thuộc loại nào _strQuery = _strQuery.toUpperCase().trim(); if (_strQuery.startsWith("SELECT ")) { _commandQuery = "SELECT"; } else if (_strQuery.startsWith("INSERT ")) { _commandQuery = "INSERT"; } else if (_strQuery.startsWith("UPDATE ")) { _commandQuery = "UPDATE"; } else if (_strQuery.startsWith("DELETE ")) { _commandQuery = "DELETE"; } else { System.out.println("----------------LOI----------------"); return false; } if (XuLyLenh()) { return true; } return false; } // set strQuery public void SetStrQuery(String str) { _strQuery = str; } public void SetTrDatabase(Database database) { _database = database; } public String GetConmmandQuery() { return _commandQuery; } public boolean CheckQuery() { if (_queryLevels < 1) { return false; } if ((_commandQuery.compareTo("SELECT") == 0 && _queryLevels > 2) || (_commandQuery.compareTo("UPDATE") == 0 && _queryLevels > 1) || (_commandQuery.compareTo("DELETE") == 0 && _queryLevels > 1)) { return false; } return true; } private int CountString(String subStr, String str) { int count = 0; int index = 0; while (true) { index = str.indexOf(subStr, index); if (index != -1) { count++; index += subStr.length(); } else { break; } } return count; } public boolean XuLyLenh() { switch (_commandQuery) { case "SELECT": if (!XuLyLenhSELECT()) { return false; } break; case "INSERT": if (!XuLyLenhINSERT()) { return false; } break; case "UPDATE": if (!XuLyLenhUPDATE()) { return false; } break; case "DELETE": if (!XuLyDELETE()) { return false; } break; } return true; } //Sử lý trường hợp là lệnh SELECT private boolean XuLyLenhSELECT() { boolean isDKWhere = true; _queryLevels = CountString("SELECT", _strQuery); int indexSelect = _strQuery.indexOf("SELECT"); int indexFrom = _strQuery.indexOf("FROM"); if (indexFrom == -1) { return false; } int indexWhere = _strQuery.indexOf("WHERE"); if (indexWhere == -1) { _soDKOWhere = 0; isDKWhere = false; indexWhere = _strQuery.length(); } //Sang thêm trường hợp cho select * if (_strQuery.contains("*")) { _dsColumn = null; } else { _dsColumn = _strQuery.substring(indexSelect + 6, indexFrom).trim().split(","); System.out.print("Danh sach cot duoc chon: "); for (int i = 0; i < _dsColumn.length; i++) { _dsColumn[i] = _dsColumn[i].trim(); System.out.print(_dsColumn[i] + " "); } } _dsTable = _strQuery.substring(indexFrom + 4, indexWhere).trim().split(","); System.out.println("Cac chi so SELECT, FROM, WHERE: " + indexSelect + " " + indexFrom + " " + indexWhere); System.out.println(); System.out.print("Danh sach bang duoc chon: "); for (int i = 0; i < _dsTable.length; i++) { _dsTable[i] = _dsTable[i].trim(); System.out.print(_dsTable[i] + " "); } System.out.println(); if (!isDKWhere) { setDKNhanDuoc(null); setDsColumnNhanDuoc(null); setDsDieuKienNhanDuoc(null); return true; } String strDieuKien = _strQuery.substring(indexWhere + 5).trim(); System.out.println("Chuoi dieu kien: " + strDieuKien); //Trường hợp lồng đơn giản WhereParse_HaveSelect parseSelect = null; if (_queryLevels == 2) { //select mssv, hoten from sinhvien where mssv in (select mssv from sinhvien) parseSelect = new WhereParse_HaveSelect(strDieuKien, _database); parseSelect.ExecuteTableReturnHaveColumnFromSelect(); _tempTableForLongCap = parseSelect.getTable(); //Đổi lại strDieuKien chỉ từ where tới "(" strDieuKien = _strQuery.substring(indexWhere + 5, _strQuery.indexOf("(")); _soDKOWhere = 1; for (int i = 0; i < _dsDKKiemTra.length; i++) { if (strDieuKien.contains(_dsDKKiemTra[i])) { setDKNhanDuoc(_dsDKKiemTra[i]); System.out.println("Dieu kien " + _dsDKKiemTra[i]); } } } else { //Trường hợp where nhiều hơn một điều kiện if (strDieuKien.contains("OR") || strDieuKien.contains("AND")) { _soDKOWhere = 2; WhereParse wp = new WhereParse(strDieuKien); setDsColumnNhanDuoc(wp.getDSCotNhanDuoc()); setDsDieuKienNhanDuoc(wp.getDSDKNhanDuoc()); setDsValueNhanDuoc(wp.getDSValueNhanDuoc()); setDkOWhere(wp.getDK()); for (int i = 0; i < 2; i++) { System.out.println(getDsColumnNhanDuoc()[i] + getDsDieuKienNhanDuoc()[i] + getDsValueNhanDuoc()[i]); } } //Trường hợp where chỉ có một điều kiện đơn thuần else { _soDKOWhere = 1; for (int i = 0; i < _dsDKKiemTra.length; i++) { if (strDieuKien.contains(_dsDKKiemTra[i])) { setDKNhanDuoc(_dsDKKiemTra[i]); setColumnNhanDuoc(strDieuKien.split(getDKNhanDuoc())[0].trim()); setValueNhanDuoc(strDieuKien.split(getDKNhanDuoc())[1].trim()); System.out.println("Dieu kien " + _dsDKKiemTra[i]); System.out.println("Column " + getColumnNhanDuoc()); System.out.println("Gia tri " + getValueNhanDuoc()); //Trường hợp này cũng tương tự trường hợp khi có kết, //Khác ở chỗ ValueNhanDuoc này là cột thứ 2. Xử lý ở SQLParse //select hocsinh.mssv, hocsinh.hoten, lophoc.giaovienchunhiem where hocsinh.ma_lop = lophoc.malop //Quy định là khi kết thì đều phải có . if (_ColumnNhanDuoc.contains(".") && _valueNhanDuoc.contains(".")) { _isKetBang = true; if (_dsColumn != null) { for (int iCol = 0; iCol < _dsColumn.length; iCol++) { if (!_dsColumn[iCol].contains(".")) { _isKetBang = false; break; } } break; } } } } } } return true; } public String catCotTuChuoi(String str) { int index = str.indexOf("."); if (index == -1) { return str; } return str.substring(index); } private boolean XuLyLenhUPDATE() { boolean isDKWhere = false; int indexUpdate = _strQuery.indexOf("UPDATE"); int indexSet = _strQuery.indexOf("SET"); int indexWhere = _strQuery.indexOf("WHERE"); if (indexWhere == -1) { indexWhere = _strQuery.length(); isDKWhere = true; } String tableUpdate = _strQuery.substring(indexUpdate + 6, indexSet).toUpperCase().trim(); _tableUpdate = _database.getTable(tableUpdate); if (_tableUpdate == null) { System.out.println("_tableUpdate = null trong String_Query"); return false; } String[] strColumnValueSet = _strQuery.substring(indexSet + 3, indexWhere).trim().split("="); int numberColumnUpdate = strColumnValueSet.length - 1; _dsColumn = new String[numberColumnUpdate]; _dsValue = new String[numberColumnUpdate]; System.out.println(tableUpdate); int iColumn = 0; int iValue = 0; for (int i = 0; i < numberColumnUpdate; i++) { if (!strColumnValueSet[i].contains(",")) { _dsColumn[iColumn] = strColumnValueSet[i].trim(); iColumn++; } else { _dsValue[iValue] = strColumnValueSet[i].split(",", 2)[0].trim().toUpperCase(); iValue++; _dsColumn[iColumn] = strColumnValueSet[i].split(",", 2)[1].trim(); iColumn++; } } _dsValue[iValue] = strColumnValueSet[numberColumnUpdate].trim().toUpperCase(); iValue++; for (int i = 0; i < numberColumnUpdate; i++) { System.out.print(_dsColumn[i] + " "); } System.out.println(); for (int i = 0; i < numberColumnUpdate; i++) { System.out.print(_dsValue[i] + " "); } System.out.println(); if (isDKWhere) { System.out.println("Khong co dieu kien where"); } else { String strDieuKien = _strQuery.substring(indexWhere + 5).trim(); System.out.println("Chuoi dieu kien: " + strDieuKien); //Trường hợp where nhiều hơn một điều kiện if (strDieuKien.contains("OR") || strDieuKien.contains("AND")) { _soDKOWhere = 2; WhereParse wp = new WhereParse(strDieuKien); setDsColumnNhanDuoc(wp.getDSCotNhanDuoc()); setDsDieuKienNhanDuoc(wp.getDSDKNhanDuoc()); setDsValueNhanDuoc(wp.getDSValueNhanDuoc()); setDkOWhere(wp.getDK()); for (int i = 0; i < 2; i++) { System.out.println(getDsColumnNhanDuoc()[i] + getDsDieuKienNhanDuoc()[i] + getDsValueNhanDuoc()[i]); } } else { for (int i = 0; i < _dsDKKiemTra.length; i++) { if (strDieuKien.contains(_dsDKKiemTra[i])) { _soDKOWhere = 1; setDKNhanDuoc(_dsDKKiemTra[i]); setColumnNhanDuoc(strDieuKien.split(getDKNhanDuoc())[0].trim()); setValueNhanDuoc(strDieuKien.split(getDKNhanDuoc())[1].trim()); System.out.println("Dieu kien " + _dsDKKiemTra[i]); System.out.println("Column " + getColumnNhanDuoc()); System.out.println("Gia tri " + getValueNhanDuoc()); } } } } return true; } //DELETE FROM Persons //WHERE LastName='Tjessem' AND FirstName='Jakob' private boolean XuLyDELETE() { boolean isDKWhere = true; int indexDELETE = _strQuery.indexOf("DELETE"); int indexFROM = _strQuery.indexOf(" FROM "); if (indexFROM == -1)//nếu không có mệnh đề from { return false; } int indexWHERE = _strQuery.indexOf(" WHERE "); if (indexWHERE == -1) { indexWHERE = _strQuery.length(); isDKWhere = false; } _dsTable = _strQuery.substring(indexFROM + 5, indexWHERE).trim().split(","); if (_dsTable.length != 1) { return false; } System.out.println("Bang ma co delete: " + _dsTable[0]); if (!isDKWhere) {//Delete From SinhVien _soDKOWhere = 0; System.out.println("Xoa het noi dung bang: " + _dsTable[0]); } else { String strDieuKien = _strQuery.substring(indexWHERE + 6).trim(); System.out.println("Chuoi dieu kien: " + strDieuKien); //Trường hợp where nhiều hơn một điều kiện if (strDieuKien.contains("OR") || strDieuKien.contains("AND")) { _soDKOWhere = 2; WhereParse wp = new WhereParse(strDieuKien); setDsColumnNhanDuoc(wp.getDSCotNhanDuoc()); setDsDieuKienNhanDuoc(wp.getDSDKNhanDuoc()); setDsValueNhanDuoc(wp.getDSValueNhanDuoc()); setDkOWhere(wp.getDK()); for (int i = 0; i < 2; i++) { System.out.println(getDsColumnNhanDuoc()[i] + getDsDieuKienNhanDuoc()[i] + getDsValueNhanDuoc()[i]); } } else { _soDKOWhere = 1; for (int i = 0; i < _dsDKKiemTra.length; i++) { if (strDieuKien.contains(_dsDKKiemTra2[i])) { setDKNhanDuoc(_dsDKKiemTra2[i]); setColumnNhanDuoc(strDieuKien.split(getDKNhanDuoc())[0].trim()); setValueNhanDuoc(strDieuKien.split(getDKNhanDuoc())[1].trim()); System.out.println("Dieu kien " + _dsDKKiemTra2[i]); System.out.println("Column " + getColumnNhanDuoc()); System.out.println("Gia tri " + getValueNhanDuoc()); //break; Vì > và >= } return true; } } } return true; } /* * Hàm Insert Lấy Table insert Tại bảng _dsTable; Hàm Insert Lấy Value tại * bảng _dsValue */ private boolean XuLyLenhINSERT() { //INSERT INTO table_name VALUES (value1, value2, value3,...) _commandQuery = "INSERT"; int IntoPos = _strQuery.indexOf(" INTO "); int ValuesPos = _strQuery.indexOf(" VALUES"); int BeginBrack = _strQuery.indexOf("("); int EndBrack = _strQuery.indexOf(")"); //kiểm tra nếu không có 1 trong 4 trường trên thì sẽ bị lỗi if ((IntoPos != -1) && (ValuesPos != -1) && (BeginBrack != -1) && (EndBrack != -1)) { _dsTable = _strQuery.substring(IntoPos + 5, ValuesPos).trim().split(","); if (_dsTable.length != 1) //kiểm tra nếu khác 1 bảng { return false; } _dsValue = _strQuery.substring(BeginBrack + 1, EndBrack).trim().split(","); if (_dsValue.length <= 0)//kiểm tra nếu không có dữ liệu thêm vào { return false; } return true; } return false; } /** * @return the _DKNhanDuoc */ public String getDKNhanDuoc() { return _DKNhanDuoc; } /** * @param DKNhanDuoc the _DKNhanDuoc to set */ public void setDKNhanDuoc(String DKNhanDuoc) { this._DKNhanDuoc = DKNhanDuoc; } /** * @return the _ColumnNhanDuoc */ public String getColumnNhanDuoc() { return _ColumnNhanDuoc; } /** * @param ColumnNhanDuoc the _ColumnNhanDuoc to set */ public void setColumnNhanDuoc(String ColumnNhanDuoc) { this._ColumnNhanDuoc = ColumnNhanDuoc; } /** * @return the _valueNhanDuoc */ public String getValueNhanDuoc() { return _valueNhanDuoc; } /** * @param valueNhanDuoc the _valueNhanDuoc to set */ public void setValueNhanDuoc(String valueNhanDuoc) { this._valueNhanDuoc = valueNhanDuoc; } /** * @return the _dsColumnNhanDuoc */ public String[] getDsColumnNhanDuoc() { return _dsColumnNhanDuoc; } /** * @param dsColumnNhanDuoc the _dsColumnNhanDuoc to set */ public void setDsColumnNhanDuoc(String[] dsColumnNhanDuoc) { this._dsColumnNhanDuoc = dsColumnNhanDuoc; } /** * @return the _dsValueNhanDuoc */ public String[] getDsValueNhanDuoc() { return _dsValueNhanDuoc; } /** * @param dsValueNhanDuoc the _dsValueNhanDuoc to set */ public void setDsValueNhanDuoc(String[] dsValueNhanDuoc) { this._dsValueNhanDuoc = dsValueNhanDuoc; } /** * @return the _dsDieuKienNhanDuoc */ public String[] getDsDieuKienNhanDuoc() { return _dsDieuKienNhanDuoc; } /** * @param dsDieuKienNhanDuoc the _dsDieuKienNhanDuoc to set */ public void setDsDieuKienNhanDuoc(String[] dsDieuKienNhanDuoc) { this._dsDieuKienNhanDuoc = dsDieuKienNhanDuoc; } /** * @return the _dkOWhere */ public String getDkOWhere() { return _dkOWhere; } /** * @param dkOWhere the _dkOWhere to set */ public void setDkOWhere(String dkOWhere) { this._dkOWhere = dkOWhere; } //dsColumn và dsValue cho trương hợp comment update public String[] getDsColumn() { return _dsColumn; } public String[] getDsValue() { return _dsValue; } /** * @return the _dsTable */ public String[] getDsTable() { return _dsTable; } /** * @param dsTable the _dsTable to set */ public void setDsTable(String[] dsTable) { this._dsTable = dsTable; } public int getSoDKOWhere() { return _soDKOWhere; } /** * @return the _dsValue */ public Table getTableTempForLongCap() { return _tempTableForLongCap; } public int getQueryLevels() { return _queryLevels; } public Table getTableUpdate() { return _tableUpdate; } public boolean isKetBang() { return _isKetBang; } }
121212-doancuoiky
trunk/Do An Final/Source Code/Server/src/MyQuery/String_Query.java
Java
oos
20,399
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package server; import MyDatabase.Command; import java.io.*; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author HUYNHLOC */ public class Client extends Thread { private Socket _client; private int _index; private ObjectInputStream ois; private ObjectOutputStream oos; CommandListener _comCommandListener; DisconnectListener _disConnectListener; public Client(Socket client, int index) { try { _client = client; _index = index; oos = new ObjectOutputStream(new BufferedOutputStream(_client.getOutputStream())); oos.flush(); ois = new ObjectInputStream(new BufferedInputStream(_client.getInputStream())); } catch (IOException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } } public void SetCommandListener(CommandListener cmdlistener) { _comCommandListener = cmdlistener; } public void SetDisconnectListener(DisconnectListener disconnectlistener) { _disConnectListener = disconnectlistener; } // day su kien nhan 1 command ra ngoai public void fireReceiveCommandEvent(Command cmd) { _comCommandListener.handleReceiveCommand(this, cmd); } public void fireDisconnectEvent() { _disConnectListener.handleDisconnect(_index); } synchronized public void SendCommand(Command cmd) { SendCommandToClient Sender = new SendCommandToClient(cmd); Sender.start(); } /** * @return the _index */ public int getIndex() { return _index; } /** * @param index the _index to set */ public void setIndex(int index) { this._index = index; } class SendCommandToClient extends Thread { private Command _cmdSend; public SendCommandToClient(Command cmd) { _cmdSend = cmd; } @Override public void run() { try { oos.writeObject(_cmdSend); oos.flush(); } catch (IOException ex) { //Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } this.interrupt(); System.gc(); } } public void run() { while (_client.isConnected()) { try { Command cmdrec = (Command) ois.readObject(); fireReceiveCommandEvent(cmdrec); } catch (Exception ex) { //ex.printStackTrace(); break; } } fireDisconnectEvent(); Disconnect(); } public void Disconnect() { if (_client != null && _client.isConnected()) { try { ois.close(); oos.close(); _client.shutdownInput(); _client.shutdownOutput(); _client.close(); _client = null; } catch (IOException ex) { //Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } } } }
121212-doancuoiky
trunk/Do An Final/Source Code/Server/src/server/Client.java
Java
oos
3,446
package server; import MyDatabase.Command; interface CommandListener{ void handleReceiveCommand(Client sender,Command cmd); } interface DisconnectListener{ void handleDisconnect(int index); }
121212-doancuoiky
trunk/Do An Final/Source Code/Server/src/server/Interface.java
Java
oos
210
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package server; import MyDatabase.Column; import MyDatabase.Database; import MyDatabase.Table; import java.io.File; import java.util.EventObject; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JDialog; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; /** * * @author HUYNHLOC */ public class TableValues extends DefaultTableModel { TableValues(String[] colNames, int i) { super(colNames, i); } @Override public Class getColumnClass(int column) { Class dataType = super.getColumnClass(column); if (column == 2) { dataType = Boolean.class; } return dataType; } @Override public boolean isCellEditable(int row, int column) { if (column == 3 || column == 4) { Boolean b = (Boolean) getValueAt(row, 2); if (b == null) { b = false; } if (b) { return false; } } return true; } @Override public void setValueAt(Object value, int row, int column) { super.setValueAt(value, row, column); if (column == 2) { for (int i = 0; i < getRowCount(); i++) { if (i != row) { super.setValueAt(false, i, column); } } Boolean b = (Boolean) getValueAt(row, column); if (b == null) { b = false; } if (b) { super.setValueAt(null, row, 3); super.setValueAt(null, row, 4); } } } // kiem tra co du lieu hay khong public Boolean AllDataValid() { Vector Datas = this.getDataVector(); for (int i = 0; i < Datas.size(); i++) { if (!this.isValid((Vector) Datas.elementAt(i))) { return false; } } return true; } //kiem tra hop le cua mot row public boolean isValid(Vector data) { if (data.elementAt(0) == null || data.elementAt(0).toString().trim().equals("") || data.elementAt(1) == null || data.elementAt(1).toString().trim().equals("")) { return false; } if (data.elementAt(3) == null || data.elementAt(3).toString().trim().equals("")){ if (data.elementAt(4) != null && !data.elementAt(4).toString().trim().equals("")) return false; } if (data.elementAt(4) == null || data.elementAt(4).toString().trim().equals("")){ if (data.elementAt(3) != null && !data.elementAt(3).toString().trim().equals("")) return false; } return true; } // chuyen du lieu thanh kieu Table public boolean WriteTableToDatabase(String tablename, Database database) { if (!this.AllDataValid()) { return false; } Table table = new Table(tablename); Vector Datas = this.getDataVector(); for (int i = 0; i < Datas.size(); i++) { Vector data = (Vector) Datas.elementAt(i); if (this.isValid(data)) { String namecol = data.elementAt(0).toString().trim(); String strtype = data.elementAt(1).toString().trim(); int type = strtype.equals("String") ? 1 : 0; Boolean isprimarykey = (Boolean) data.elementAt(2); if (isprimarykey == null) { isprimarykey = false; } Boolean isforeignkey; String namecolref; String nametableref; Table taberef = null; if (data.elementAt(3) == null || data.elementAt(3).toString().trim().equals("")) { isforeignkey = false; namecolref = ""; nametableref = ""; } else { isforeignkey = true; namecolref = data.elementAt(3).toString().trim(); nametableref = data.elementAt(4).toString().trim(); taberef = database.getTable(nametableref); if (taberef == null) { return false; } } if (!table.addColumn(namecol, namecolref, taberef, type, isprimarykey, isforeignkey)) { return false; } } } /* * // vi du tao table SINHVIEN va add row vao Vector<Object> row1 = new * Vector<Object>(); row1.add("0912268"); row1.add("Huynh Van Loc"); * table.addRow(row1); Vector<Object> row2 = new Vector<Object>(); * row2.add("0912359"); row2.add("Pham Duy Phuong"); table.addRow(row2); * */ if (!database.addTable(table)) { return false; } database.showDatabase(); return true; } }
121212-doancuoiky
trunk/Do An Final/Source Code/Server/src/server/TableValues.java
Java
oos
5,445
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package server; import MyDatabase.*; import SQLParse.SQLParser; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.Vector; /** * * @author HUYNHLOC */ public class ServerListener extends Thread { // so client dang connect private int countClient = 0; private int _port; // danh sach client Vector<Client> _listClien; //database Data _myData; // SqlParse SQLParser _sqlLParser; public ServerListener(int port, Data data) { _port = port; _listClien = new Vector<Client>(); _myData = data; _sqlLParser = new SQLParser(); _myData.show(); } public void run() { try { // lang nghe ket noi ServerSocket serverSocket = new ServerSocket(_port); while (true) { // socket lang nghe ket noi Socket soc = serverSocket.accept(); countClient++; Client client = new Client(soc, countClient); client.SetCommandListener(new ReceiveCommandListener()); client.SetDisconnectListener(new ClientDisconnectListener()); _listClien.add(client); client.start(); this.BroadCastListDatabase(); } } catch (IOException ex) { //Logger.getLogger(ServerListener.class.getName()).log(Level.SEVERE, null, ex); } } public void Disconnect() { for (int i = 0; i < _listClien.size(); i++) { ((Client) _listClien.elementAt(i)).Disconnect(); } _listClien.clear(); this.interrupt(); } // su ly command nhan duoc class ReceiveCommandListener implements CommandListener { @Override synchronized public void handleReceiveCommand(Client sender, Command cmd) { Client client = (Client) sender; Command.CommandType cmdType = (Command.CommandType) cmd.getCmdType(); switch (cmdType) { case Query: //JOptionPane.showMessageDialog(null, cmd.getMessage(), "Query", 1); /* * Table table = _myDatabase.getTable(cmd.getMessage()); * Command cmdsend = new * Command(Command.CommandType.TableData, table); * client.SendCommand(cmdsend); * */ /* * SQLParser qLParser = new SQLParser(cmd.getMessage()); * Table table = qLParser.SQLResult(_myDatabase); if(table * == null){ //Command cmdSend = new * Command(Command.CommandType.Message, "Loi hoac ko co du * lieu"); client.SendCommand(cmdSend); }else{ // co du lieu * Command cmdSend = new * Command(Command.CommandType.TableData, table); * client.SendCommand(cmdSend); } * */ String[] queryanddatabase = cmd.getMessage().split("/"); String query = queryanddatabase[0].trim(); String nameDatabase = queryanddatabase[1].trim(); Database database = _myData.getDatabase(nameDatabase); // query //nkluan doi lai cho nay thanh kieu boolean boolean Kiemtra = _sqlLParser.setQuery(query, database); //Table table = qLParser.SQLResult(); //boolean Kiemtra = _sqlLParser.SQLResult(); if (Kiemtra) { if (_sqlLParser.GetQueryComment().compareTo("SELECT") == 0) {//neu kiem tra dung va do la menh de select Table table = _sqlLParser.getTableResult(); if (table == null) { Command cmdSend = new Command(Command.CommandType.Message, "Loi hoac ko co du lieu"); client.SendCommand(cmdSend); } else { // co du lieu Command cmdSend = new Command(Command.CommandType.TableData, table); client.SendCommand(cmdSend); } } else//khong phai menh de select thao tac thanh cong { ////////////SANG Table table = _sqlLParser.getTableResult(); if (table == null) { Command cmdSend = new Command(Command.CommandType.Message, "Loi hoac ko co du lieu"); client.SendCommand(cmdSend); } else { // co du lieu String queryGetTableDisplay = "select * from " + table.getNameTable(); _sqlLParser.setQuery(queryGetTableDisplay, database); Table tableDisplay = _sqlLParser.getTableResult(); //Lệnh này là select nên sử lý lại select thành công Command cmdSend = new Command(Command.CommandType.TableData, tableDisplay); client.SendCommand(cmdSend); } /* * try { Thread.sleep(1000); } catch * (InterruptedException ex) { * Logger.getLogger(ServerListener.class.getName()).log(Level.SEVERE, * null, ex); } Table result = * database.getTable(_sqlLParser.getDStable()[0]); * Command cmdSend = new * Command(Command.CommandType.TableData, result); * client.SendCommand(cmdSend); * */ } } else//thao tac khong thanh cong { Command cmdSend = new Command(Command.CommandType.Message, "Thao tac that bai"); client.SendCommand(cmdSend); } break; // nhan duoc mot message case Message: break; } } } // broadcasdt command public void BroadCastCommand(Command cmd) { for (int i = 0; i < _listClien.size(); i++) { _listClien.get(i).SendCommand(cmd); } } // broadcasd danh sach database public void BroadCastListDatabase() { ArrayList list = _myData.getAllNameDatabases(); String message = " "; for (int i = 0; i < list.size(); i++) { message += " " + (String) list.get(i); } Command cmd = new Command(Command.CommandType.ListNameDatabase, message.trim()); this.BroadCastCommand(cmd); } class ClientDisconnectListener implements DisconnectListener { @Override public void handleDisconnect(int index) { for (int i = 0; i < _listClien.size(); i++) { if (((Client) _listClien.elementAt(i)).getIndex() == index) { _listClien.remove(i); } } } } public Data getData() { return _myData; } }
121212-doancuoiky
trunk/Do An Final/Source Code/Server/src/server/ServerListener.java
Java
oos
8,012
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package server; import MyDatabase.*; import java.awt.Color; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.DefaultCellEditor; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JOptionPane; import javax.swing.event.CellEditorListener; import javax.swing.event.ChangeEvent; import javax.swing.table.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.*; import org.xml.sax.SAXException; /** * * @author HUYNHLOC */ public class MainWindow extends javax.swing.JFrame { /** * Creates new form MainWSindow */ TableValues model; Document doc; // tai lieu xml ServerListener server; Data _myData; JComboBox jcb_forTableNameRef; //list name table trong mot database ArrayList _listNameTable; public MainWindow() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jButton_start = new javax.swing.JButton(); jButton_stop = new javax.swing.JButton(); jTextField_port = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jTextField_nametable = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jTextField_namedatabase = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jButton_createdatabase = new javax.swing.JButton(); jComboBox_database = new javax.swing.JComboBox(); jLabel3 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jTable_maintable = new javax.swing.JTable(); jButton_addrow = new javax.swing.JButton(); jButton_deleterow = new javax.swing.JButton(); jButton_createtable = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("MainWindow"); setResizable(false); addWindowListener(new java.awt.event.WindowAdapter() { public void windowActivated(java.awt.event.WindowEvent evt) { formWindowActivated(evt); } public void windowClosed(java.awt.event.WindowEvent evt) { formWindowClosed(evt); } public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } public void windowOpened(java.awt.event.WindowEvent evt) { formWindowOpened(evt); } }); jPanel1.setBackground(java.awt.SystemColor.activeCaption); jButton_start.setText("Start"); jButton_start.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_startActionPerformed(evt); } }); jButton_stop.setText("Stop"); jButton_stop.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_stopActionPerformed(evt); } }); jTextField_port.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { jTextField_portKeyTyped(evt); } }); jLabel2.setText("Port"); jLabel1.setText("Name table :"); jLabel4.setText("Name Database"); jButton_createdatabase.setText("Create Database"); jButton_createdatabase.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_createdatabaseActionPerformed(evt); } }); jComboBox_database.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox_databaseActionPerformed(evt); } }); jLabel3.setText("List Database"); jTable_maintable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(jTable_maintable); jButton_addrow.setText("Add Column"); jButton_addrow.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_addrowActionPerformed(evt); } }); jButton_deleterow.setText("Delete Column"); jButton_deleterow.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_deleterowActionPerformed(evt); } }); jButton_createtable.setText("Create Table"); jButton_createtable.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_createtableActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 537, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jButton_start, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton_stop, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 139, Short.MAX_VALUE) .addComponent(jButton_createdatabase, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField_port, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField_nametable, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(50, 50, 50) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3) .addGap(21, 21, 21) .addComponent(jComboBox_database, 0, 174, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTextField_namedatabase)))))))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jButton_addrow) .addGap(14, 14, 14) .addComponent(jButton_deleterow) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton_createtable) .addGap(8, 8, 8))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField_port, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2) .addComponent(jTextField_namedatabase, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton_start) .addComponent(jButton_stop) .addComponent(jButton_createdatabase)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 62, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jTextField_nametable, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3) .addComponent(jComboBox_database, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(15, 15, 15) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton_addrow) .addComponent(jButton_deleterow) .addComponent(jButton_createtable)) .addGap(11, 11, 11)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated // TODO add your handling code here: }//GEN-LAST:event_formWindowActivated private void jButton_addrowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_addrowActionPerformed // TODO add your handling code here: //model.insertRow(model.getRowCount(), new Object[]{}); model.addRow(new Object[]{}); }//GEN-LAST:event_jButton_addrowActionPerformed private void jButton_createtableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_createtableActionPerformed // TODO add your handling code here: if (jTextField_nametable.getText().trim().equals("") || !model.AllDataValid()) { JOptionPane.showMessageDialog(MainWindow.this, "Chưa nhập tên hoặc dữ liệu không hơp lệ", "Loi", 1); } else { // ghi table xuong database if (model.WriteTableToDatabase(jTextField_nametable.getText().trim(), _myData.getDatabase((String) jComboBox_database.getSelectedItem()))) { JOptionPane.showMessageDialog(rootPane, "Tạo bảng thành công", "Thong bao", 1); _listNameTable.add(jTextField_nametable.getText().trim()); // delete old table for (int i = 0; i < model.getDataVector().size(); i++) { model.removeRow(i); } model.removeRow(0); // them danh sach table String databaseSelected = (String) jComboBox_database.getSelectedItem(); Database database = _myData.getDatabase(databaseSelected); if (database != null) { _listNameTable.clear(); _listNameTable = database.getAllNameTable(); jcb_forTableNameRef.removeAllItems(); for (int i = 0; i < _listNameTable.size(); i++) { jcb_forTableNameRef.addItem(_listNameTable.get(i)); } jcb_forTableNameRef.addItem(" "); } } else { JOptionPane.showMessageDialog(rootPane, "Tên hoặc dữ liệu không hợp lệ", "Thong bao", 1); } } }//GEN-LAST:event_jButton_createtableActionPerformed private void jButton_startActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_startActionPerformed // TODO add your handling code here: try { if (jTextField_port.getText().trim().equals("")) { JOptionPane.showMessageDialog(MainWindow.this, "Thieu thong tin input", "Loi", 1); } else { server = new ServerListener(Integer.parseInt(jTextField_port.getText().trim()), _myData); server.start(); jButton_start.setVisible(false); jButton_stop.setVisible(true); } } catch (Exception e) { } }//GEN-LAST:event_jButton_startActionPerformed private void jTextField_portKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField_portKeyTyped // TODO add your handling code here: Character c = evt.getKeyChar(); if (c > '9' || c < '0') { evt.consume(); } }//GEN-LAST:event_jTextField_portKeyTyped private void jButton_stopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_stopActionPerformed // TODO add your handling code here: // luu da ta xuong co so du lieu server.Disconnect(); jButton_start.setVisible(true); jButton_stop.setVisible(false); }//GEN-LAST:event_jButton_stopActionPerformed private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened // TODO add your handling code here: initGUI(); jButton_start.setVisible(true); jButton_stop.setVisible(false); }//GEN-LAST:event_formWindowOpened private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed // TODO add your handling code here: server.Disconnect(); }//GEN-LAST:event_formWindowClosed private void jButton_deleterowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_deleterowActionPerformed // TODO add your handling code here: if (jTable_maintable.getSelectedRow() >= 0) { model.removeRow(jTable_maintable.getSelectedRow()); } }//GEN-LAST:event_jButton_deleterowActionPerformed private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing // TODO add your handling code here: if (server != null) { server.Disconnect(); } try { // ghi du lieu xuong file if (_myData != null) { Server_Data.SerialDatabase("MyData.txt", _myData); } } catch (FileNotFoundException ex) { Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_formWindowClosing private void jButton_createdatabaseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_createdatabaseActionPerformed // TODO add your handling code here: if (jTextField_namedatabase.getText().trim().equals("")) { JOptionPane.showMessageDialog(MainWindow.this, "Nhập tên database", "Loi", 1); } else { Database database = new Database(jTextField_namedatabase.getText().trim()); if (_myData.addDatabase(database)) { JOptionPane.showMessageDialog(MainWindow.this, "Thao tác thành công", "Thong bao", 1); jComboBox_database.addItem(database.getName()); if (server != null) { // gởi danh sach cac database server.BroadCastListDatabase(); } } else { JOptionPane.showMessageDialog(MainWindow.this, "Database da ton tai", "Loi", 1); } } }//GEN-LAST:event_jButton_createdatabaseActionPerformed private void jComboBox_databaseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox_databaseActionPerformed // TODO add your handling code here: String databaseSelected = (String) jComboBox_database.getSelectedItem(); Database database = _myData.getDatabase(databaseSelected); if (database != null) { _listNameTable.clear(); _listNameTable = database.getAllNameTable(); jcb_forTableNameRef.removeAllItems(); for (int i = 0; i < _listNameTable.size(); i++) { jcb_forTableNameRef.addItem(_listNameTable.get(i)); } jcb_forTableNameRef.addItem(" "); } }//GEN-LAST:event_jComboBox_databaseActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* * Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* * If Nimbus (introduced in Java SE 6) is not available, stay with the * default look and feel. For details see * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* * Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { MainWindow mainWindow = new MainWindow(); mainWindow.setLocation(400, 200); mainWindow.setVisible(true); } }); } public void initGUI() { String[] colNames = {"Field", "DataType", "PrimaryKey", "ColNameRef", "TableNameref"}; model = new TableValues(colNames, 1); jTable_maintable.setModel(model); JComboBox jComboBox = new JComboBox(); jComboBox.addItem("String"); jComboBox.addItem("Int"); DefaultCellEditor dce = new DefaultCellEditor(jComboBox); TableColumnModel tcm = jTable_maintable.getColumnModel(); TableColumn tc = tcm.getColumn(1); tc.setCellEditor(dce); jcb_forTableNameRef = new JComboBox(); _listNameTable = new ArrayList(); try {// load data File f = new File("MyData.txt"); if (!f.exists()) { f.createNewFile(); Data data = new Data(); Database systemdatabase = new Database("SYSTEM"); data.addDatabase(systemdatabase); Server_Data.SerialDatabase("MyData.txt", data); } _myData = Server_Data.Deseriable("MyData.txt"); ArrayList nameDatabases = _myData.getAllNameDatabases(); for (int i = 0; i < nameDatabases.size(); i++) { jComboBox_database.addItem((String) nameDatabases.get(i)); } } catch (FileNotFoundException ex) { Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex); } DefaultCellEditor dce_tablenameref = new DefaultCellEditor(jcb_forTableNameRef); TableColumnModel tcm_tablenameref = jTable_maintable.getColumnModel(); TableColumn tc_tablenameref = tcm.getColumn(4); tc_tablenameref.setCellEditor(dce_tablenameref); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton_addrow; private javax.swing.JButton jButton_createdatabase; private javax.swing.JButton jButton_createtable; private javax.swing.JButton jButton_deleterow; private javax.swing.JButton jButton_start; private javax.swing.JButton jButton_stop; private javax.swing.JComboBox jComboBox_database; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable_maintable; private javax.swing.JTextField jTextField_namedatabase; private javax.swing.JTextField jTextField_nametable; private javax.swing.JTextField jTextField_port; // End of variables declaration//GEN-END:variables }
121212-doancuoiky
trunk/Do An Final/Source Code/Server/src/server/MainWindow.java
Java
oos
25,340
#include <cmath> #include <iostream> #include <QVBoxLayout> #include <QFileDialog> #include <QDir> #include <QSize> #include <QSizePolicy> #include "Panel.hpp" #include "Drawing.hpp" Panel::Panel(QWidget *parent) : QWidget(parent) { QVBoxLayout *vbox; QHBoxLayout *box; vbox = new QVBoxLayout(); file = new QGroupBox("File"); vbox->addWidget(file); box = new QHBoxLayout; name = new QLabel("Name:"); name->setFixedWidth(200); box->addWidget(name); open = new QPushButton("Open..."); open->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); box->addWidget(open); file->setLayout(box); front = new QGroupBox("Direction"); vbox->addWidget(front); box = new QHBoxLayout; cw = new QRadioButton("Clockwise"); box->addWidget(cw); ccw = new QRadioButton("Counter-Clockwise"); box->addWidget(ccw); ccw->setChecked(true); front->setLayout(box); front->setEnabled(false); view = new QGroupBox("Primitive"); vbox->addWidget(view); box = new QHBoxLayout; point = new QRadioButton("Point"); box->addWidget(point); frame = new QRadioButton("Frame"); box->addWidget(frame); solid = new QRadioButton("Solid"); box->addWidget(solid); frame->setChecked(true); view->setLayout(box); view->setEnabled(false); color = new QGroupBox("Color"); vbox->addWidget(color); box = new QHBoxLayout; red = new QSpinBox(); red->setPrefix("R = "); red->setRange(0, 255); red->setValue(255); red->setSingleStep(5); box->addWidget(red); green = new QSpinBox(); green->setPrefix("G = "); green->setRange(0, 255); green->setValue(255); green->setSingleStep(5); box->addWidget(green); blue = new QSpinBox(); blue->setPrefix("B = "); blue->setRange(0, 255); blue->setValue(255); blue->setSingleStep(5); box->addWidget(blue); color->setLayout(box); color->setEnabled(false); trans = new QGroupBox("Translation"); vbox->addWidget(trans); box = new QHBoxLayout; movx = new QDoubleSpinBox(); movx->setPrefix("X = "); box->addWidget(movx); movy = new QDoubleSpinBox(); movy->setPrefix("Y = "); box->addWidget(movy); movz = new QDoubleSpinBox(); movz->setPrefix("Z = "); box->addWidget(movz); trans->setLayout(box); trans->setEnabled(false); rotat = new QGroupBox("Rotate"); vbox->addWidget(rotat); box = new QHBoxLayout; rotx = new QDoubleSpinBox(); rotx->setPrefix("X = "); rotx->setRange(0, 360); rotx->setSingleStep(5); rotx->setWrapping(true); box->addWidget(rotx); roty = new QDoubleSpinBox(); roty->setPrefix("Y = "); roty->setRange(0, 360); roty->setSingleStep(5); roty->setWrapping(true); box->addWidget(roty); rotz = new QDoubleSpinBox(); rotz->setPrefix("Z = "); rotz->setRange(0, 360); rotz->setSingleStep(5); rotz->setWrapping(true); box->addWidget(rotz); rotat->setLayout(box); rotat->setEnabled(false); QHBoxLayout *hbox = new QHBoxLayout; vbox->addLayout(hbox); clip = new QGroupBox("Clipping"); hbox->addWidget(clip); box = new QHBoxLayout; nearer = new QDoubleSpinBox(); nearer->setPrefix("Near = "); nearer->setRange(0, 255); box->addWidget(nearer); farer = new QDoubleSpinBox(); farer->setPrefix("Far = "); farer->setRange(0, 255); box->addWidget(farer); clip->setLayout(box); clip->setEnabled(false); reset = new QPushButton("Reset\nCamera"); reset->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); reset->setEnabled(false); hbox->addWidget(reset); setLayout(vbox); sigmap = new QSignalMapper; connect(sigmap, SIGNAL(mapped(QString)), this, SLOT(getvalue(QString))); connect(open, SIGNAL(clicked()), this, SLOT(openfile())); connect(cw, SIGNAL(clicked()), sigmap, SLOT(map())); connect(ccw, SIGNAL(clicked()), sigmap, SLOT(map())); connect(point, SIGNAL(clicked()), sigmap, SLOT(map())); connect(frame, SIGNAL(clicked()), sigmap, SLOT(map())); connect(solid, SIGNAL(clicked()), sigmap, SLOT(map())); connect(red, SIGNAL(valueChanged(int)), sigmap, SLOT(map())); connect(green, SIGNAL(valueChanged(int)), sigmap, SLOT(map())); connect(blue, SIGNAL(valueChanged(int)), sigmap, SLOT(map())); connect(movx, SIGNAL(valueChanged(double)), sigmap, SLOT(map())); connect(movy, SIGNAL(valueChanged(double)), sigmap, SLOT(map())); connect(movz, SIGNAL(valueChanged(double)), sigmap, SLOT(map())); connect(rotx, SIGNAL(valueChanged(double)), sigmap, SLOT(map())); connect(roty, SIGNAL(valueChanged(double)), sigmap, SLOT(map())); connect(rotz, SIGNAL(valueChanged(double)), sigmap, SLOT(map())); connect(nearer, SIGNAL(valueChanged(double)), sigmap, SLOT(map())); connect(farer, SIGNAL(valueChanged(double)), sigmap, SLOT(map())); connect(reset, SIGNAL(clicked()), this, SLOT(resetpara())); sigmap->setMapping(cw, "struct"); sigmap->setMapping(ccw, "struct"); sigmap->setMapping(point, "struct"); sigmap->setMapping(frame, "struct"); sigmap->setMapping(solid, "struct"); sigmap->setMapping(red, "color"); sigmap->setMapping(green, "color"); sigmap->setMapping(blue, "color"); sigmap->setMapping(movx, "trans"); sigmap->setMapping(movy, "trans"); sigmap->setMapping(movz, "trans"); sigmap->setMapping(rotx, "rotat"); sigmap->setMapping(roty, "rotat"); sigmap->setMapping(rotz, "rotat"); sigmap->setMapping(nearer, "clip"); sigmap->setMapping(farer, "clip"); } void Panel::openfile() { QString filename = QFileDialog::getOpenFileName(this, "Open File ...", QDir::currentPath(), "Input (*.in);;All (*.*)"); if(filename.isNull()) return; QString labeltxt = "Name: " + filename.section('/', -1); QFontMetrics metrics(name->font()); QString shortlabel = metrics.elidedText(labeltxt, Qt::ElideRight, name->width()); name->setText(shortlabel); emit setfilename(filename.toStdString().c_str()); } inline double min3(double x, double y, double z) { x = x < y ? x : y; return x < z ? x : z; } inline double step(double r) { return floor(r) / 50; } void Panel::initpara(double movxmin, double movxmax, double movymin, double movymax, double movzmin, double movzmax, double nearmin, double farmax) { reset->setEnabled(true); front->setEnabled(true); view->setEnabled(true); color->setEnabled(true); trans->setEnabled(true); rotat->setEnabled(true); clip->setEnabled(true); movx->setRange(movxmin, movxmax); movy->setRange(movymin, movymax); movz->setRange(movzmin, movzmax); movx->setSingleStep(step(min3(movxmax - movxmin, movymax - movymin, movzmax - movzmin))); movy->setSingleStep(step(min3(movxmax - movxmin, movymax - movymin, movzmax - movzmin))); movz->setSingleStep(step(min3(movxmax - movxmin, movymax - movymin, movzmax - movzmin))); nearer->setRange(nearmin, farmax); farer->setRange(nearmin, farmax); nearer->setSingleStep(step(farmax - nearmin)); farer->setSingleStep(step(farmax - nearmin)); getvalue("struct"); getvalue("color"); resetpara(); } void Panel::resetpara() { movx->setValue(0); movy->setValue(0); movz->setValue(0); rotx->setValue(0); roty->setValue(0); rotz->setValue(0); nearer->setValue(nearer->minimum()); farer->setValue(farer->maximum()); getvalue("trans"); getvalue("rotat"); getvalue("rotat"); getvalue("clip"); emit resetcam(); } void Panel::getvalue(const QString &v) { if(v == "struct") emit setstruct(cw->isChecked(), 'p' * point->isChecked() + 'f' * frame->isChecked() + 's' * solid->isChecked()); else if(v == "color") emit setcolor(red->value(), green->value(), blue->value()); else if(v == "trans") emit settrans(movx->value(), movy->value(), movz->value()); else if(v == "rotat") emit setrotat(rotx->value(), roty->value(), rotz->value()); else if(v == "clip"){ nearer->setMaximum(farer->value()); farer->setMinimum(nearer->value()); emit setclip(nearer->value(), farer->value()); }else std::cerr << "Panel::getvalue(): Unknown value " << v.toStdString() << std::endl; }
0nf8eypg284wijc9ovi9wfkl1yg691b
cg2/Panel.cpp
C++
gpl2
7,719
#include "Parameter.hpp" #include <GL/gl.h> #include <iostream> #include <cstdio> #include <cmath> #include <cstdlib> void UserParameter::init() { facefront = GL_CCW; for(int i = 0;i<3;i++){ color[i]=255; rotation[i]=0; translation[i]=0; } nearer = 0.1; farer = 6; primitive = GL_LINE; rotated = false; } void UserParameter::reset() { settrans(0,0,0); setrotat(0,0,0); setrotat(0,0,0); //setclip(nearmin,farmax); } void UserParameter::setstruct(bool clockwise, char view) { if(clockwise==TRUE){ facefront =GL_CW; std::cout << "Clockwise: " << clockwise << '\t' << "View: "; } else facefront = GL_CCW; switch(view){ case 'p': primitive = GL_POINT; std::cout << "Point" << std::endl; break; case 'f': primitive = GL_LINE; std::cout << "Frame" << std::endl; break; case 's': primitive = GL_FILL; std::cout << "Solid" << std::endl; break; default: std::cout << "Unknown" << std::endl; break; } emit refresh(); } void UserParameter::setcolor(int red, int green, int blue) { color[0]=red; color[1]=green; color[2]=blue; std::cout << "Color: " << red << ", " << green << ", " << blue << std::endl; emit refresh(); } void UserParameter::settrans(float x, float y, float z) { translation[0]=x; translation[1]=y; translation[2]=z; std::cout << "Translation: " << x << ", " << y << ", " << z << std::endl; emit refresh(); } void UserParameter::setrotat(float x, float y, float z) { rotationold[0] = rotation[0]; rotationold[1] = rotation[1]; rotationold[2] = rotation[2]; rotation[0] = x; rotation[1] = y; rotation[2] = z; std::cout << "Rotation: " << x << ", " << y << ", " << z << std::endl; rotated = true; emit refresh(); rotated = false; } void UserParameter::setclip(float n, float f) { nearer = n; farer = f; std::cout << "Near: " << n << '\t' << "Far" << f << std::endl; emit refresh(); } inline float fmax(float x, float y) { return x>y?x:y; } inline float fmin(float x, float y) { return x<y?x:y; } void InputParameter::readfile(const char *FileName) { char ch; FILE* fp = fopen(FileName,"r"); if (fp==NULL) { printf("ERROR: unable to open TriObj [%s]!\n",FileName); exit(1); } fscanf(fp, "%c", &ch); while(ch!= '\n') // skip the first line fscanf(fp, "%c", &ch); fscanf(fp,"# triangles = %d\n", &trinum); // read # of triangles fscanf(fp,"Material count = %d\n", &marnum); // read material count // mat.resize(marnum); for(int i=0; i<marnum; i++) { fscanf(fp, "ambient color %f %f %f\n", &mat[i].acolor[0], &mat[i].acolor[1], &mat[i].acolor[2]); fscanf(fp, "diffuse color %f %f %f\n", &mat[i].dcolor[0], &mat[i].dcolor[1], &mat[i].dcolor[2]); fscanf(fp, "specular color %f %f %f\n", &mat[i].scolor[0], &mat[i].scolor[1], &mat[i].scolor[2]); fscanf(fp, "material shine %f\n", &mat[i].shine); } // fscanf(fp, "%c", &ch); while(ch!= '\n') // skip documentation line fscanf(fp, "%c", &ch); printf ("Reading in %s (%d triangles). . .\n", FileName, trinum); tri.resize(trinum); for (int i=0; i<trinum; i++) // read triangles { for (int j=0;j<3;j++) { fscanf(fp, "v%c %f %f %f %f %f %f %d\n", &ch, &(tri[i].v[j].pos[0]), &(tri[i].v[j].pos[1]), &(tri[i].v[j].pos[2]), &(tri[i].v[j].norm[0]), &(tri[i].v[j].norm[1]), &(tri[i].v[j].norm[2]), &(tri[i].v[j].matind)); tri[i].color[j] =(unsigned char)(int)(255*(mat[tri[i].v[0].matind].dcolor[j]));//Since very vertex use the same material index, so here I take the first vertex as its color } fscanf(fp, "face normal %f %f %f\n", &(tri[i].fnorm[0]), &(tri[i].fnorm[1]), &(tri[i].fnorm[2])); } // get the max and min of the object in x y z for(int i = 0; i < 3; i++) pmax[i] = pmin[i] = tri[0].v[0].pos[i]; for(int i = 0; i < trinum; i++) { for(int j = 0; j < 3; j++) { for(int k = 0; k < 3; k++) { if(tri[i].v[j].pos[k] < pmin[k]) pmin[k] = tri[i].v[j].pos[k]; else if(tri[i].v[j].pos[k] > pmax[k]) pmax[k] = tri[i].v[j].pos[k]; } } } distance = fmax(pmax[1] - pmin[1],pmax[0] - pmin[0])* sqrt(3.0); float translate_scaler[3]; translate_scaler[0] = fmin(fmin(pmax[0] - pmin[0],pmax[1] - pmin[1]),pmax[2] -pmin[2]); translate_scaler[1] = translate_scaler[0]; translate_scaler[2] = translate_scaler[0]; float nearer_scaler = distance; float farer_scaler = distance; fclose(fp); emit initpara(-10*translate_scaler[0], 10*translate_scaler[0], -10*translate_scaler[1], 10*translate_scaler[1], -10*translate_scaler[2], 10*translate_scaler[2], 0.1*nearer_scaler, 5*farer_scaler); emit reset(); }
0nf8eypg284wijc9ovi9wfkl1yg691b
cg2/Parameter.cpp
C++
gpl2
4,549
#ifndef MATRIXDRAWING_HPP #define MATRIXDRAWING_HPP #include <QtOpenGL/QGLWidget> #include <string> #include <vector> #include <QGLShaderProgram> #include <QGLShader> using std::vector; using std::string; class MatrixDrawing : public QGLWidget { Q_OBJECT public: float u[3],v[3],n[3]; float translate[3]; float last_translate[3]; float rotation[3]; float last_rotation[3]; float translate_scaler[3]; float nearer_scaler; float farer_scaler; float fovy; float aspect; explicit MatrixDrawing(QWidget *parent = 0); QSize sizeHint() const; void initializeGL(); void paintGL(); void resizeGL(int width, int height); void CameraRotation(); void readfile(const char *Filename); struct userparameter { GLenum facefront; float color[3]; float rotation[3]; float translation[3]; float nearer; float farer; GLenum primitive; userparameter(); }; userparameter uipara; struct parameter { struct material { float acolor[3]; float dcolor[3]; float scolor[3]; float shine; }; struct triangle { struct vertex { float pos[3]; float norm[3]; int matind; }; vertex v[3]; float fnorm[3]; float color[3]; }; string name; int trinum; int marnum; vector<material> mat; vector<triangle> tri; float pmax[3], pmin[3]; float distance; }; parameter para; struct cameraparameter { float eye[3]; float center[3]; float up[3]; }; cameraparameter cpara; struct matrix { float m[16]; matrix(); void MatrixMult(float* b); // a = b* a void IdentityMatrix(); }; matrix modelviewmat,projectionmat; void getTMatrix(float x, float y, float z, GLfloat* temp); void getRMatrix(float x, float y, float z, GLfloat* temp); void CalcProjectionMatrix(); struct matrixshader { QGLShaderProgram program; GLint modelview_loc, projection_loc; }; matrixshader mshader; void LoadShaders(); private: signals: void initpara(double movxmin, double movxmax, double movymin, double movymax, double movzmin, double movzmax, double nearmin, double farmax); public slots: void Initalvalue(); void setfilename(const char *fn); void setstruct(bool clockwise, char view); void setcolor(int red, int green, int blue); void settrans(float x, float y, float z); void setrotat(float x, float y, float z); void setclip(float nearer, float farer); }; #endif // MATRIXDRAWING_HPP
0nf8eypg284wijc9ovi9wfkl1yg691b
cg2/MatrixDrawing.hpp
C++
gpl2
2,989
#ifndef __unix__ #include <windows.h> #endif #include <GL/glu.h> #include <QColor> #include <QSizePolicy> #include <QtOpenGL/QtOpenGL> #include "Drawing.hpp" #include <iostream> #include <fstream> #include <string> #include <vector> #include <cstdio> #include <math.h> void Drawing::reset() { cameraorientation[0] = cameraorientation[5] = cameraorientation[10] =cameraorientation[15] = 1; cameraorientation[1] = cameraorientation[2] = cameraorientation[3] =cameraorientation[4] =cameraorientation[6] = cameraorientation[7] = cameraorientation[8] =cameraorientation[9] =cameraorientation[11] = cameraorientation[12] = cameraorientation[13] =cameraorientation[14] =0; u[0]=v[1]=n[2]=1; u[1]=u[2]=v[0]=v[2]=n[1]=n[0]=0; for(int i=0;i<3;i++) { rotation[i]=0; translate[i]=0; } refresh(); } void Drawing::CameraRotation() { glPushMatrix(); glMatrixMode(GL_MODELVIEW_MATRIX); glLoadIdentity(); glRotatef(rotation[0],1,0,0); glRotatef(rotation[1],0,1,0); glRotatef(rotation[2],0,0,1); glMultMatrixf(cameraorientation); glGetFloatv(GL_MODELVIEW_MATRIX,cameraorientation); glPopMatrix(); for(int i=0;i<3;i++) { u[i]=cameraorientation[4*i]; v[i]=cameraorientation[4*i+1]; n[i]=cameraorientation[4*i+2]; } } Drawing::Drawing(QWidget *parent) : QGLWidget(QGLFormat(QGL::SampleBuffers), parent) { setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); } QSize Drawing::sizeHint() const { return QSize(256, 256); } void Drawing::initializeGL() { makeCurrent(); glShadeModel(GL_SMOOTH); glClearColor(1.0,1.0,1.0,0.0); glClearDepth(1.0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST); } void Drawing::paintGL() { makeCurrent(); //glUseProgram(0); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glMatrixMode(GL_MODELVIEW); glColor3ub(uipara->color[0],uipara->color[1],uipara->color[2]); glPolygonMode(GL_FRONT,uipara->primitive); glFrontFace(uipara->facefront); for(int i=0;i<inpara->trinum;i++) { glBegin(GL_TRIANGLES); glVertex3f(inpara->tri[i].v[0].pos[0],inpara->tri[i].v[0].pos[1],inpara->tri[i].v[0].pos[2]); glVertex3f(inpara->tri[i].v[1].pos[0],inpara->tri[i].v[1].pos[1],inpara->tri[i].v[1].pos[2]); glVertex3f(inpara->tri[i].v[2].pos[0],inpara->tri[i].v[2].pos[1],inpara->tri[i].v[2].pos[2]); glEnd(); } glCullFace(GL_BACK); } void Drawing::resizeGL(int width, int height) { makeCurrent(); glViewport(0,0,width,height); glClearColor(0,0,0,0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt((inpara->pmax[0]+inpara->pmin[0])/2+translate[0], (inpara->pmax[1]+inpara->pmin[1])/2+translate[1], (inpara->pmax[2]+inpara->pmin[2])/2+translate[2]+inpara->distance, (inpara->pmax[0]+inpara->pmin[0])/2+translate[0]-n[0], (inpara->pmax[1]+inpara->pmin[1])/2+translate[1]-n[1], (inpara->pmax[2]+inpara->pmin[2])/2+translate[2]+inpara->distance-n[2], v[0],v[1],v[2]); /* GLfloat temp[16]; glGetFloatv(GL_MODELVIEW_MATRIX,temp); std::cout<<"GM:"; for(int ii =0; ii<16; ii++) std::cout<<temp[ii]<<' '; std::cout<<std::endl; */ glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0,width/height,uipara->nearer,uipara->farer); } void Drawing::refresh() { for(int i=0;i<3;i++){ translate[i] = uipara->translation[0]*u[i] +uipara->translation[1]*v[i] +uipara->translation[2]*n[i]; } if(uipara->rotated){ cout << "rotate: "; for(int i = 0; i < 3; i++){ rotation[i] = uipara->rotation[i] - uipara->rotationold[i]; cout << rotation[i] << ','; } cout << endl; CameraRotation(); } resizeGL(width(), height()); updateGL(); }
0nf8eypg284wijc9ovi9wfkl1yg691b
cg2/Drawing.cpp
C++
gpl2
3,680
#include <QGLWidget> #include <QtOpenGL/QtOpenGL> #include <QColor> #include <QSizePolicy> #include <QFileInfo> #include <iostream> #include <fstream> #include <cstdio> //#include <string> //#include <vector> #include "MatrixDrawing.hpp" #include <GL/glu.h> #include <GL/gl.h> #include <QMatrix4x4> void MatrixDrawing::Initalvalue() { u[0]=v[1]=n[2]=1.0f; u[1]=u[2]=v[0]=v[2]=n[1]=n[0]=0.0f; for(int i=0;i<3;i++) { rotation[i]=0.0f; last_rotation[i]=0.0f; translate[i]=0.0f; last_translate[i]=0.0f; uipara.rotation[i]=0.0f; uipara.translation[i]=0.0f; } fovy = 60.0/180.0*3.1415926; aspect = width()/height(); modelviewmat.IdentityMatrix(); GLfloat temp[16]; getTMatrix(-(para.pmin[0]+para.pmax[0])/2,-(para.pmin[1]+para.pmax[1])/2,-(para.pmax[2]+para.pmin[2])/2-para.distance,temp); modelviewmat.MatrixMult(temp); projectionmat.IdentityMatrix(); CalcProjectionMatrix(); } MatrixDrawing::userparameter::userparameter() { facefront = GL_CCW; for(int i = 0;i<3;i++) { color[i]=255; rotation[i]=0.0f; translation[i]=0.0f; } nearer = 0.1; farer = 6.0; primitive = GL_LINE; } MatrixDrawing::matrix::matrix() { IdentityMatrix(); } void MatrixDrawing::matrix::IdentityMatrix() { for(int ii=0;ii<16;ii++) m[ii]=0.0f; for(int ii = 0;ii<4;ii++) m[5*ii]=1.0f; } void MatrixDrawing::matrix::MatrixMult(GLfloat* b) // a = b* a { float temp[16]; for(int ii=0; ii<16; ii++){ temp[ii]=m[ii]; m[ii] = 0.0f; } for(int ii=0; ii<4; ii++) for (int jj = 0;jj<4;jj++) for(int kk = 0;kk<4;kk++) m[4*jj+ii] += b[4*kk+ii]*temp[4*jj+kk]; } void MatrixDrawing::getTMatrix(float x, float y, float z, GLfloat* temp) { glPushMatrix(); glMatrixMode(GL_MODELVIEW_MATRIX); glLoadIdentity(); glTranslatef(x,y,z); glGetFloatv(GL_MODELVIEW_MATRIX,temp); glPopMatrix(); } void MatrixDrawing::getRMatrix(float x, float y, float z, GLfloat *temp) { glPushMatrix(); glMatrixMode(GL_MODELVIEW_MATRIX); glLoadIdentity(); glRotatef(x,1.0f,0.0f,0.0f); glRotatef(y,0.0f,1.0f,0.0f); glRotatef(z,0.0f,0.0f,1.0f); glGetFloatv(GL_MODELVIEW_MATRIX,temp); glPopMatrix(); } void MatrixDrawing::CalcProjectionMatrix() { GLfloat f = 1/tan(fovy/2); projectionmat.IdentityMatrix(); projectionmat.m[0]=f/aspect; projectionmat.m[5]=f; projectionmat.m[10]=(uipara.farer+uipara.nearer)/(uipara.nearer-uipara.farer); projectionmat.m[11]=-1.0; projectionmat.m[14]=2*uipara.farer*uipara.nearer/(uipara.nearer-uipara.farer); projectionmat.m[15]=0.0; } void MatrixDrawing::CameraRotation() { GLfloat temp[16]; getRMatrix(rotation[0],rotation[1],rotation[2],temp); modelviewmat.MatrixMult(temp); //update camera for(int i=0;i<3;i++) { u[i]=modelviewmat.m[4*i]; v[i]=modelviewmat.m[4*i+1]; n[i]=modelviewmat.m[4*i+2]; } } inline float fmax(float x, float y) { return x>y?x:y; } inline float fmin(float x, float y) { return x<y?x:y; } void MatrixDrawing::readfile(const char *FileName) { Initalvalue(); char ch; FILE* fp = fopen(FileName,"r"); if (fp==NULL) { printf("ERROR: unable to open TriObj [%s]!\n",FileName); exit(1); } fscanf(fp, "%c", &ch); while(ch!= '\n') // skip the first line fscanf(fp, "%c", &ch); fscanf(fp,"# triangles = %d\n", &para.trinum); // read # of triangles fscanf(fp,"Material count = %d\n", &para.marnum); // read material count // para.mat.resize(para.marnum); for(int i=0; i<para.marnum; i++) { fscanf(fp, "ambient color %f %f %f\n", &para.mat[i].acolor[0], &para.mat[i].acolor[1], &para.mat[i].acolor[2]); fscanf(fp, "diffuse color %f %f %f\n", &para.mat[i].dcolor[0], &para.mat[i].dcolor[1], &para.mat[i].dcolor[2]); fscanf(fp, "specular color %f %f %f\n", &para.mat[i].scolor[0], &para.mat[i].scolor[1], &para.mat[i].scolor[2]); fscanf(fp, "material shine %f\n", &para.mat[i].shine); } // fscanf(fp, "%c", &ch); while(ch!= '\n') // skip documentation line fscanf(fp, "%c", &ch); printf ("Reading in %s (%d triangles). . .\n", FileName, para.trinum); para.tri.resize(para.trinum); for (int i=0; i<para.trinum; i++) // read triangles { for (int j=0;j<3;j++) { fscanf(fp, "v%c %f %f %f %f %f %f %d\n", &ch, &(para.tri[i].v[j].pos[0]), &(para.tri[i].v[j].pos[1]), &(para.tri[i].v[j].pos[2]), &(para.tri[i].v[j].norm[0]), &(para.tri[i].v[j].norm[1]), &(para.tri[i].v[j].norm[2]), &(para.tri[i].v[j].matind)); para.tri[i].color[j] =(unsigned char)(int)(255*(para.mat[para.tri[i].v[0].matind].dcolor[j]));//Since very vertex use the same material index, so here I take the first vertex as its color } fscanf(fp, "face normal %f %f %f\n", &(para.tri[i].fnorm[0]), &(para.tri[i].fnorm[1]), &(para.tri[i].fnorm[2])); } // get the max and min of the object in x y z for(int i = 0; i < 3; i++) para.pmax[i] = para.pmin[i] = para.tri[0].v[0].pos[i]; for(int i = 0; i < para.trinum; i++) { for(int j = 0; j < 3; j++) { for(int k = 0; k < 3; k++) { if(para.tri[i].v[j].pos[k] < para.pmin[k]) para.pmin[k] = para.tri[i].v[j].pos[k]; else if(para.tri[i].v[j].pos[k] > para.pmax[k]) para.pmax[k] = para.tri[i].v[j].pos[k]; } } } para.distance = fmax(para.pmax[1] - para.pmin[1],para.pmax[0] - para.pmin[0])* sqrt(3.0); translate_scaler[0] = fmin(fmin(para.pmax[0] - para.pmin[0],para.pmax[1] - para.pmin[1]),para.pmax[2] -para.pmin[2]); translate_scaler[1] = translate_scaler[0]; translate_scaler[2] = translate_scaler[0]; nearer_scaler = para.distance; farer_scaler = para.distance; fclose(fp); modelviewmat.IdentityMatrix(); GLfloat temp[16]; getTMatrix(-(para.pmin[0]+para.pmax[0])/2,-(para.pmin[1]+para.pmax[1])/2,-(para.pmax[2]+para.pmin[2])/2-para.distance,temp); modelviewmat.MatrixMult(temp); projectionmat.IdentityMatrix(); CalcProjectionMatrix(); std::cout<<"SMReadfile:"; for(int ii =0; ii<16; ii++) std::cout<<modelviewmat.m[ii]<<' '; std::cout<<std::endl; } MatrixDrawing::MatrixDrawing(QWidget *parent) : QGLWidget(QGLFormat(QGL::SampleBuffers), parent) { setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); } QSize MatrixDrawing::sizeHint() const { return QSize(256, 256); } void MatrixDrawing::initializeGL() { makeCurrent(); LoadShaders(); glShadeModel(GL_SMOOTH); glClearColor(1.0,1.0,1.0,0.0); glClearDepth(1.0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST); } void MatrixDrawing::paintGL() { makeCurrent(); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); CalcProjectionMatrix(); glColor3ub(uipara.color[0],uipara.color[1],uipara.color[2]); glPolygonMode(GL_FRONT,uipara.primitive); glFrontFace(uipara.facefront); glBegin(GL_TRIANGLES); for(int i=0;i<para.trinum;i++) { glVertex3f(para.tri[i].v[0].pos[0],para.tri[i].v[0].pos[1],para.tri[i].v[0].pos[2]); glVertex3f(para.tri[i].v[1].pos[0],para.tri[i].v[1].pos[1],para.tri[i].v[1].pos[2]); glVertex3f(para.tri[i].v[2].pos[0],para.tri[i].v[2].pos[1],para.tri[i].v[2].pos[2]); } glEnd(); glCullFace(GL_BACK); //mshader.program.release(); //mshader.program.removeAllShaders(); } void MatrixDrawing::resizeGL(int width, int height) { makeCurrent(); glViewport(0,0,width,height); glClearColor(0,0,0,0); projectionmat.IdentityMatrix(); CalcProjectionMatrix(); mshader.modelview_loc = mshader.program.uniformLocation("modelviewmat"); mshader.projection_loc = mshader.program.uniformLocation("projectionmat"); mshader.program.setUniformValue(mshader.modelview_loc,QMatrix4x4((const qreal*)modelviewmat.m).transposed()); mshader.program.setUniformValue(mshader.projection_loc,QMatrix4x4((const qreal*)projectionmat.m).transposed()); std::cout<<"SM:"; for(int ii =0; ii<16; ii++) std::cout<<modelviewmat.m[ii]<<' '; std::cout<<std::endl; /* std::cout<<"shader projection"; for(int ii =0; ii<15; ii++) std::cout<<projectionmat.m[ii]<<' '; std::cout<<std::endl;*/ } void MatrixDrawing::setfilename(const char *fn) { readfile(fn); // std::cout << "Open File: " << fn << std::endl; //emit initpara(-10*translate_scaler[0], 10*translate_scaler[0], -10*translate_scaler[1], 10*translate_scaler[1], -10*translate_scaler[2], 10*translate_scaler[2], 0.1*nearer_scaler, 5*farer_scaler); //initializeGL(); makeCurrent(); resizeGL(width(), height()); // paintGL(); updateGL(); /* glewInit(); if (glewIsSupported("GL_VERSION_2_0")) printf("Ready for OpenGL 2.0\n"); else { printf("OpenGL 2.0 not supported\n"); exit(1); }*/ } void MatrixDrawing::setstruct(bool clockwise, char view) { if(clockwise==TRUE){ uipara.facefront =GL_CW; std::cout << "Clockwise: " << clockwise << '\t' << "View: "; } else uipara.facefront = GL_CCW; switch(view){ case 'p': uipara.primitive = GL_POINT; std::cout << "Point" << std::endl; break; case 'f': uipara.primitive = GL_LINE; std::cout << "Frame" << std::endl; break; case 's': uipara.primitive = GL_FILL; std::cout << "Solid" << std::endl; break; default: std::cout << "Unknown" << std::endl; break; } resizeGL(width(), height()); //paintGL(); updateGL(); } void MatrixDrawing::setcolor(int red, int green, int blue) { uipara.color[0]=red; uipara.color[1]=green; uipara.color[2]=blue; resizeGL(width(), height()); //paintGL(); updateGL(); // setShaders(); //std::cout << "Color: " << red << ", " << green << ", " << blue << std::endl; } void MatrixDrawing::settrans(float x, float y, float z) { for(int i=0;i<3;i++) { translate[i]=0; } uipara.translation[0]=x; uipara.translation[1]=y; uipara.translation[2]=z; /* for(int i=0;i<3;i++) { translate[i] = (uipara.translation[0]-last_translate[0])*u[i] +(uipara.translation[1]-last_translate[1])*v[i] +(uipara.translation[2]-last_translate[2])*n[i]; } */ for(int i=0;i<3;i++) { translate[i] = uipara.translation[i]-last_translate[i]; } last_translate[0]=x; last_translate[1]=y; last_translate[2]=z; GLfloat temp[16]; getTMatrix(-translate[0],-translate[1],-translate[2],temp); modelviewmat.MatrixMult(temp); /* for(int ii = 12;ii<15;ii++) modelviewmat.m[ii]=0; getTMatrix(-(para.pmin[0]+para.pmax[0])/2,-(para.pmin[1]+para.pmax[1])/2,-(para.pmax[2]+para.pmin[2])/2-para.distance,temp2); modelviewmat.MatrixMult(temp2); modelviewmat.MatrixMult(temp1);*/ resizeGL(width(), height()); //paintGL(); updateGL(); // setShaders(); //std::cout << "Translation: " << x << ", " << y << ", " << z << std::endl; } void MatrixDrawing::setrotat(float x, float y, float z) { rotation[0] = x-uipara.rotation[0]; rotation[1] = y-uipara.rotation[1]; rotation[2] = z-uipara.rotation[2]; uipara.rotation[0] = x; uipara.rotation[1] = y; uipara.rotation[2] = z; CameraRotation(); resizeGL(width(), height()); // paintGL(); updateGL(); // setShaders(); //std::cout << "Rotation: " << x << ", " << y << ", " << z << std::endl; } void MatrixDrawing::setclip(float nearer, float farer) { uipara.nearer = nearer; uipara.farer = farer; resizeGL(width(), height()); //paintGL(); updateGL(); // setShaders(); //std::cout << "Near: " << nearer << '\t' << "Far" << farer << std::endl; } void MatrixDrawing::LoadShaders() { std::cout<< "LoadShaders()" << std::endl; /* char *vs = NULL,*fs = NULL; QGLShader vshader(QGLShader::Vertex); QGLShader fshader(QGLShader::Fragment); vs = textFileRead("vertexshader.txt"); fs = textFileRead("fragshader.txt"); vshader.compileSourceCode(vs); fshader.compileSourceCode(fs); vshader.log(); fshader.log(); if(mshader.program) { mshader.program.release(); mshader.program.removeAllShaders(); } else mshader.program = new QGLShaderProgram; */ if(!mshader.program.isLinked()) { if(!mshader.program.addShaderFromSourceCode(QGLShader::Vertex, "uniform mat4 modelviewmat, projectionmat;\n" "void main(void)\n" "{\n" " gl_FrontColor = gl_Color;\n" " gl_Position = projectionmat*modelviewmat*gl_Vertex;\n" "}\n")) { qWarning()<<"Vertex Shader source file"<<mshader.program.log(); } if(!mshader.program.addShaderFromSourceCode(QGLShader::Fragment, "void main(void)\n" "{\n" " gl_FragColor = gl_Color;" "}\n")) { qWarning()<<"Fragment Shader source file"<<mshader.program.log(); } if(!mshader.program.link()) { qWarning()<<"Shader Program Linker Error" << mshader.program.log(); } mshader.program.bind(); } }
0nf8eypg284wijc9ovi9wfkl1yg691b
cg2/MatrixDrawing.cpp
C++
gpl2
14,109
#ifndef PANEL_HPP #define PANEL_HPP #include <QWidget> #include <QSignalMapper> #include <QLabel> #include <QGroupBox> #include <QPushButton> #include <QRadioButton> #include <QSpinBox> #include <QDoubleSpinBox> class Panel : public QWidget { Q_OBJECT public: explicit Panel(QWidget *parent = 0); QSignalMapper *sigmap; QGroupBox *file; QLabel *name; QPushButton *open; QPushButton *reset; QGroupBox *front; QRadioButton *cw; QRadioButton *ccw; QGroupBox *view; QRadioButton *point; QRadioButton *frame; QRadioButton *solid; QGroupBox *color; QSpinBox *red; QSpinBox *green; QSpinBox *blue; QGroupBox *trans; QDoubleSpinBox *movx; QDoubleSpinBox *movy; QDoubleSpinBox *movz; QGroupBox *rotat; QDoubleSpinBox *rotx; QDoubleSpinBox *roty; QDoubleSpinBox *rotz; QGroupBox *clip; QDoubleSpinBox *nearer; QDoubleSpinBox *farer; signals: void setfilename(const char *fn); void setstruct(bool clockwise, char viewtype); void setcolor(int red, int green, int blue); void settrans(float x, float y, float z); void setrotat(float x, float y, float z); void setclip(float n, float f); void resetcam(); public slots: void initpara(double movxmin, double movxmax, double movymin, double movymax, double movzmin, double movzmax, double nearmin, double farmax); void openfile(); void getvalue(const QString &v); void resetpara(); }; #endif // PANEL_HPP
0nf8eypg284wijc9ovi9wfkl1yg691b
cg2/Panel.hpp
C++
gpl2
1,404
#ifndef DEBUG_H #define DEBUG_H #include <iostream> #define OUT(x) std::cout << x << std::endl #endif // DEBUG_H
0nf8eypg284wijc9ovi9wfkl1yg691b
cg2/debug.h
C++
gpl2
116
#ifndef PARAMETER_HPP #define PARAMETER_HPP #include <QObject> #include <GL/gl.h> #include <vector> #include <string> using namespace std; class UserParameter : public QObject { Q_OBJECT public: GLenum facefront; float color[3]; float rotation[3]; float rotationold[3]; bool rotated; float translation[3]; float nearer; float farer; GLenum primitive; void init(); UserParameter(){init();} signals: void refresh(); public slots: void reset(); void setstruct(bool clockwise, char view); void setcolor(int red, int green, int blue); void settrans(float x, float y, float z); void setrotat(float x, float y, float z); void setclip(float n, float f); }; class InputParameter : public QObject { Q_OBJECT public: struct material { float acolor[3]; float dcolor[3]; float scolor[3]; float shine; }; struct triangle { struct vertex { float pos[3]; float norm[3]; int matind; }; vertex v[3]; float fnorm[3]; float color[3]; }; string name; int trinum; int marnum; vector<material> mat; vector<triangle> tri; float pmax[3], pmin[3]; float distance; signals: void initpara(double movxmin, double movxmax, double movymin, double movymax, double movzmin, double movzmax, double nearmin, double farmax); void reset(); public slots: void readfile(const char* file); }; #endif // PARAMETER_HPP
0nf8eypg284wijc9ovi9wfkl1yg691b
cg2/Parameter.hpp
C++
gpl2
1,469
#ifndef MAINWINDOW_HPP #define MAINWINDOW_HPP #include <QMainWindow> #include <QtGui> #include "Panel.hpp" #include "Drawing.hpp" #include "MatrixDrawing.hpp" class MainWindow : public QMainWindow { Q_OBJECT public: Panel *bottom; Drawing *left; MatrixDrawing *right; UserParameter uipara; InputParameter inpara; MainWindow(QWidget *parent = 0); ~MainWindow(); public slots: }; #endif // MAINWINDOW_HPP
0nf8eypg284wijc9ovi9wfkl1yg691b
cg2/MainWindow.hpp
C++
gpl2
417
#include "MainWindow.hpp" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { setCentralWidget(new QFrame); QVBoxLayout *vbox = new QVBoxLayout; QHBoxLayout *hbox = new QHBoxLayout; left = new Drawing; left->uipara = &uipara; left->inpara = &inpara; right = new MatrixDrawing; bottom = new Panel; left->initializeGL(); //right->initializeGL(); hbox->addWidget(left); hbox->addWidget(right); vbox->addLayout(hbox); vbox->addWidget(bottom); centralWidget()->setLayout(vbox); connect(bottom, SIGNAL(setfilename(const char*)), &inpara, SLOT(readfile(const char*))); connect(&inpara, SIGNAL(initpara(double,double,double,double,double,double,double,double)), bottom, SLOT(initpara(double,double,double,double,double,double,double,double))); connect(bottom, SIGNAL(setstruct(bool,char)), &uipara, SLOT(setstruct(bool,char))); connect(bottom, SIGNAL(setcolor(int,int,int)), &uipara, SLOT(setcolor(int,int,int))); connect(bottom, SIGNAL(settrans(float,float,float)), &uipara, SLOT(settrans(float,float,float))); connect(bottom, SIGNAL(setrotat(float,float,float)), &uipara, SLOT(setrotat(float,float,float))); connect(bottom, SIGNAL(setclip(float,float)), &uipara, SLOT(setclip(float,float))); connect(&uipara, SIGNAL(refresh()), left, SLOT(refresh())); connect(&inpara, SIGNAL(reset()), left, SLOT(reset())); connect(bottom, SIGNAL(resetcam()), left, SLOT(reset())); //connect(bottom, SIGNAL(initialdrawing()), left, SLOT(Initalvalue())); /* // connect(right, SIGNAL(initpara(double,double,double,double,double,double,double,double)), // bottom, SLOT(initpara(double,double,double,double,double,double,double,double))); connect(bottom, SIGNAL(setfilename(const char*)), right, SLOT(setfilename(const char*))); connect(bottom, SIGNAL(setstruct(bool,char)), right, SLOT(setstruct(bool,char))); connect(bottom, SIGNAL(setcolor(int,int,int)), right, SLOT(setcolor(int,int,int))); connect(bottom, SIGNAL(settrans(float,float,float)), right, SLOT(settrans(float,float,float))); connect(bottom, SIGNAL(setrotat(float,float,float)), right, SLOT(setrotat(float,float,float))); connect(bottom, SIGNAL(setclip(float,float)), right, SLOT(setclip(float,float))); //connect(bottom, SIGNAL(initialmatrixdrawing()), right, SLOT(Initalvalue())); */ } MainWindow::~MainWindow() { }
0nf8eypg284wijc9ovi9wfkl1yg691b
cg2/MainWindow.cpp
C++
gpl2
2,329
#------------------------------------------------- # # Project created by QtCreator 2012-09-23T17:26:22 # #------------------------------------------------- QT += core gui opengl greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = demo TEMPLATE = app SOURCES += main.cpp\ MainWindow.cpp \ Panel.cpp \ Drawing.cpp \ MatrixDrawing.cpp \ Parameter.cpp HEADERS += \ MainWindow.hpp \ Panel.hpp \ Drawing.hpp \ debug.h \ MatrixDrawing.hpp \ Parameter.hpp unix: LIBS += -lGLU unix: CONFIG += link_pkgconfig
0nf8eypg284wijc9ovi9wfkl1yg691b
cg2/demo.pro
QMake
gpl2
563
#include <QApplication> #include "MainWindow.hpp" int main(int argc, char *argv[]) { QApplication app(argc, argv); MainWindow w; //Window w; w.show(); return app.exec(); }
0nf8eypg284wijc9ovi9wfkl1yg691b
cg2/main.cpp
C++
gpl2
179
#ifndef DRAWING_HPP #define DRAWING_HPP #include <QtOpenGL/QGLWidget> #include <string> #include <vector> #include "Parameter.hpp" using std::vector; using std::string; class Drawing : public QGLWidget { Q_OBJECT public: explicit Drawing(QWidget *parent = 0); void initializeGL(); UserParameter *uipara; InputParameter *inpara; private: float cameraorientation[16]; float u[3],v[3],n[3]; float translate[3]; float rotation[3]; QSize sizeHint() const; void paintGL(); void resizeGL(int width, int height); void CameraRotation(); public slots: void reset(); void refresh(); }; #endif // DRAWING_HPP
0nf8eypg284wijc9ovi9wfkl1yg691b
cg2/Drawing.hpp
C++
gpl2
628
/* * Copyright (C) 2011 Jacquet Wong * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.musicg.experiment.math.cluster; public class Segment { private int startPosition; private int size; private double mean; public int getStartPosition() { return startPosition; } public void setStartPosition(int startPosition) { this.startPosition = startPosition; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } public double getMean() { return mean; } public void setMean(double mean) { this.mean = mean; } }
1018143-musicg
src/com/musicg/experiment/math/cluster/Segment.java
Java
asf20
1,142
/* * Copyright (C) 2011 Jacquet Wong * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.musicg.experiment.math.cluster; import java.util.LinkedList; import java.util.List; import com.musicg.pitch.PitchHandler; public class SegmentCluster{ private double diffThreshold; public SegmentCluster(){ this.diffThreshold=1; } public SegmentCluster(double diffThreshold){ this.diffThreshold=diffThreshold; } public void setDiffThreshold(double diffThreshold){ this.diffThreshold=diffThreshold; } public List<Segment> getSegments(double[] array){ PitchHandler pitchHandler=new PitchHandler(); List<Segment> segmentList=new LinkedList<Segment>(); double segmentMean=0; int segmentSize=0; if (array.length>0){ segmentMean=array[1]; segmentSize=1; } for (int i=1; i<array.length; i++){ double diff=Math.abs(pitchHandler.getToneChanged(array[i], segmentMean)); if (diff<diffThreshold){ // same cluster, add to the cluster and change the cluster data segmentMean=(segmentMean*segmentSize+array[i])/(++segmentSize); } else{ // not the cluster, create a new one //System.out.println("New Cluster: "+clusterMean); Segment segment=new Segment(); segment.setMean(segmentMean); segment.setStartPosition(i-segmentSize); segment.setSize(segmentSize); segmentList.add(segment); // end current cluster // set new cluster segmentMean=array[i]; segmentSize=1; } } // add the last cluster Segment segment=new Segment(); segment.setMean(segmentMean); segment.setStartPosition(array.length-segmentSize); segment.setSize(segmentSize); segmentList.add(segment); return segmentList; } }
1018143-musicg
src/com/musicg/experiment/math/cluster/SegmentCluster.java
Java
asf20
2,309
/* * Copyright (C) 2011 Jacquet Wong * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.musicg.math.statistics; /** * Evaluate the standard deviation of an array * * @author Jacquet Wong * */ public class StandardDeviation extends MathStatistics{ private Mean mean=new Mean(); public StandardDeviation(){ } public StandardDeviation(double[] values){ setValues(values); } public double evaluate(){ mean.setValues(values); double meanValue=mean.evaluate(); int size=values.length; double diffSquare=0; double sd=Double.NaN; for (int i=0; i<size; i++){ diffSquare+=Math.pow(values[i]-meanValue,2); } if (size>0){ sd=Math.sqrt(diffSquare/size); } return sd; } }
1018143-musicg
src/com/musicg/math/statistics/StandardDeviation.java
Java
asf20
1,301
/* * Copyright (C) 2011 Jacquet Wong * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.musicg.math.statistics; /** * Evaluate the centroid of an array * * @author Jacquet Wong * */ public class DataCentroid extends MathStatistics{ public DataCentroid(){ } public DataCentroid(double[] values){ setValues(values); } public double evaluate(){ double sumCentroid=0; double sumIntensities=0; int size=values.length; for (int i=0; i<size; i++){ if (values[i]>0){ sumCentroid+=i*values[i]; sumIntensities+=values[i]; } } double avgCentroid=sumCentroid/sumIntensities; return avgCentroid; } }
1018143-musicg
src/com/musicg/math/statistics/DataCentroid.java
Java
asf20
1,217
/* * Copyright (C) 2011 Jacquet Wong * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.musicg.math.statistics; /** * Abstract class for mathematics & statistics * * @author Jacquet Wong * */ public abstract class MathStatistics{ protected double[] values; public void setValues(double[] values){ this.values=values; } public abstract double evaluate(); }
1018143-musicg
src/com/musicg/math/statistics/MathStatistics.java
Java
asf20
928
/* * Copyright (C) 2011 Jacquet Wong * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.musicg.math.statistics; /** * Evaluate the zero crossing rate of a signal * * @author Jacquet Wong * */ public class ZeroCrossingRate{ private short[] signals; private double lengthInSecond; /** * Constructor * * @param signals input signal array * @param lengthInSecond length of the signal (in second) */ public ZeroCrossingRate(short[] signals, double lengthInSecond){ setSignals(signals,1); } /** * set the signals * * @param signals input signal array * @param lengthInSecond length of the signal (in second) */ public void setSignals(short[] signals, double lengthInSecond){ this.signals=signals; this.lengthInSecond=lengthInSecond; } public double evaluate(){ int numZC=0; int size=signals.length; for (int i=0; i<size-1; i++){ if((signals[i]>=0 && signals[i+1]<0) || (signals[i]<0 && signals[i+1]>=0)){ numZC++; } } return numZC/lengthInSecond; } }
1018143-musicg
src/com/musicg/math/statistics/ZeroCrossingRate.java
Java
asf20
1,609
/* * Copyright (C) 2011 Jacquet Wong * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.musicg.math.statistics; /** * Evaluate the spectral centroid of an array * * @author Jacquet Wong * */ public class SpectralCentroid extends MathStatistics{ public SpectralCentroid(){ } public SpectralCentroid(double[] values){ setValues(values); } public double evaluate(){ double sumCentroid=0; double sumIntensities=0; int size=values.length; for (int i=0; i<size; i++){ if (values[i]>0){ sumCentroid+=i*values[i]; sumIntensities+=values[i]; } } double avgCentroid=sumCentroid/sumIntensities; return avgCentroid; } }
1018143-musicg
src/com/musicg/math/statistics/SpectralCentroid.java
Java
asf20
1,238
/* * Copyright (C) 2011 Jacquet Wong * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.musicg.math.statistics; /** * Evaluate the sum of an array * * @author Jacquet Wong * */ public class Sum extends MathStatistics{ public Sum(){ } public Sum(double[] values){ setValues(values); } public double evaluate(){ double sum=0; int size=values.length; for (int i=0 ;i<size; i++){ sum+=values[i]; } return sum; } public int size(){ return values.length; } }
1018143-musicg
src/com/musicg/math/statistics/Sum.java
Java
asf20
1,061
/* * Copyright (C) 2011 Jacquet Wong * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.musicg.math.statistics; /** * Evaluate the mean of an array * @author Jacquet Wong * */ public class Mean extends MathStatistics{ private Sum sum=new Sum(); public Mean(){ } public Mean(double[] values){ setValues(values); } public double evaluate(){ sum.setValues(values); double mean=sum.evaluate()/sum.size(); return mean; } }
1018143-musicg
src/com/musicg/math/statistics/Mean.java
Java
asf20
1,006
package com.musicg.math.rank; import java.util.List; public interface MapRank{ public List getOrderedKeyList(int numKeys, boolean sharpLimit); }
1018143-musicg
src/com/musicg/math/rank/MapRank.java
Java
asf20
153
package com.musicg.math.rank; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class MapRankInteger implements MapRank{ private Map map; private boolean acsending=true; public MapRankInteger(Map<?,Integer> map, boolean acsending){ this.map=map; this.acsending=acsending; } public List getOrderedKeyList(int numKeys, boolean sharpLimit){ // if sharp limited, will return sharp numKeys, otherwise will return until the values not equals the exact key's value Set mapEntrySet=map.entrySet(); List keyList=new LinkedList(); // if the numKeys is larger than map size, limit it if (numKeys>map.size()){ numKeys=map.size(); } // end if the numKeys is larger than map size, limit it if (map.size()>0){ int[] array=new int[map.size()]; int count=0; // get the pass values Iterator<Entry> mapIterator=mapEntrySet.iterator(); while (mapIterator.hasNext()){ Entry entry=mapIterator.next(); array[count++]=(Integer)entry.getValue(); } // end get the pass values int targetindex; if (acsending){ targetindex=numKeys; } else{ targetindex=array.length-numKeys; } int passValue=getOrderedValue(array,targetindex); // this value is the value of the numKey-th element // get the passed keys and values Map passedMap=new HashMap(); List<Integer> valueList=new LinkedList<Integer>(); mapIterator=mapEntrySet.iterator(); while (mapIterator.hasNext()){ Entry entry=mapIterator.next(); int value=(Integer)entry.getValue(); if ((acsending && value<=passValue) || (!acsending && value>=passValue)){ passedMap.put(entry.getKey(), value); valueList.add(value); } } // end get the passed keys and values // sort the value list Integer[] listArr=new Integer[valueList.size()]; valueList.toArray(listArr); Arrays.sort(listArr); // end sort the value list // get the list of keys int resultCount=0; int index; if (acsending){ index=0; } else{ index=listArr.length-1; } if (!sharpLimit){ numKeys=listArr.length; } while (true){ int targetValue=(Integer)listArr[index]; Iterator<Entry> passedMapIterator=passedMap.entrySet().iterator(); while(passedMapIterator.hasNext()){ Entry entry=passedMapIterator.next(); if ((Integer)entry.getValue()==targetValue){ keyList.add(entry.getKey()); passedMapIterator.remove(); resultCount++; break; } } if (acsending){ index++; } else{ index--; } if (resultCount>=numKeys){ break; } } // end get the list of keys } return keyList; } private int getOrderedValue(int[] array, int index){ locate(array,0,array.length-1,index); return array[index]; } // sort the partitions by quick sort, and locate the target index private void locate(int[] array, int left, int right, int index) { int mid=(left+right)/2; //System.out.println(left+" to "+right+" ("+mid+")"); if (right==left){ //System.out.println("* "+array[targetIndex]); //result=array[targetIndex]; return; } if(left < right) { int s = array[mid]; int i = left - 1; int j = right + 1; while(true) { while(array[++i] < s) ; while(array[--j] > s) ; if(i >= j) break; swap(array, i, j); } //System.out.println("2 parts: "+left+"-"+(i-1)+" and "+(j+1)+"-"+right); if (i>index){ // the target index in the left partition //System.out.println("left partition"); locate(array, left, i-1,index); } else{ // the target index in the right partition //System.out.println("right partition"); locate(array, j+1, right,index); } } } private void swap(int[] array, int i, int j) { int t = array[i]; array[i] = array[j]; array[j] = t; } }
1018143-musicg
src/com/musicg/math/rank/MapRankInteger.java
Java
asf20
4,472
package com.musicg.math.rank; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class MapRankDouble implements MapRank{ private Map map; private boolean acsending=true; public MapRankDouble(Map<?,Double> map, boolean acsending){ this.map=map; this.acsending=acsending; } public List getOrderedKeyList(int numKeys, boolean sharpLimit){ // if sharp limited, will return sharp numKeys, otherwise will return until the values not equals the exact key's value Set mapEntrySet=map.entrySet(); List keyList=new LinkedList(); // if the numKeys is larger than map size, limit it if (numKeys>map.size()){ numKeys=map.size(); } // end if the numKeys is larger than map size, limit it if (map.size()>0){ double[] array=new double[map.size()]; int count=0; // get the pass values Iterator<Entry> mapIterator=mapEntrySet.iterator(); while (mapIterator.hasNext()){ Entry entry=mapIterator.next(); array[count++]=(Double)entry.getValue(); } // end get the pass values int targetindex; if (acsending){ targetindex=numKeys; } else{ targetindex=array.length-numKeys; } double passValue=getOrderedValue(array,targetindex); // this value is the value of the numKey-th element // get the passed keys and values Map passedMap=new HashMap(); List<Double> valueList=new LinkedList<Double>(); mapIterator=mapEntrySet.iterator(); while (mapIterator.hasNext()){ Entry entry=mapIterator.next(); double value=(Double)entry.getValue(); if ((acsending && value<=passValue) || (!acsending && value>=passValue)){ passedMap.put(entry.getKey(), value); valueList.add(value); } } // end get the passed keys and values // sort the value list Double[] listArr=new Double[valueList.size()]; valueList.toArray(listArr); Arrays.sort(listArr); // end sort the value list // get the list of keys int resultCount=0; int index; if (acsending){ index=0; } else{ index=listArr.length-1; } if (!sharpLimit){ numKeys=listArr.length; } while (true){ double targetValue=(Double)listArr[index]; Iterator<Entry> passedMapIterator=passedMap.entrySet().iterator(); while(passedMapIterator.hasNext()){ Entry entry=passedMapIterator.next(); if ((Double)entry.getValue()==targetValue){ keyList.add(entry.getKey()); passedMapIterator.remove(); resultCount++; break; } } if (acsending){ index++; } else{ index--; } if (resultCount>=numKeys){ break; } } // end get the list of keys } return keyList; } private double getOrderedValue(double[] array, int index){ locate(array,0,array.length-1,index); return array[index]; } // sort the partitions by quick sort, and locate the target index private void locate(double[] array, int left, int right, int index) { int mid=(left+right)/2; //System.out.println(left+" to "+right+" ("+mid+")"); if (right==left){ //System.out.println("* "+array[targetIndex]); //result=array[targetIndex]; return; } if(left < right) { double s = array[mid]; int i = left - 1; int j = right + 1; while(true) { while(array[++i] < s) ; while(array[--j] > s) ; if(i >= j) break; swap(array, i, j); } //System.out.println("2 parts: "+left+"-"+(i-1)+" and "+(j+1)+"-"+right); if (i>index){ // the target index in the left partition //System.out.println("left partition"); locate(array, left, i-1,index); } else{ // the target index in the right partition //System.out.println("right partition"); locate(array, j+1, right,index); } } } private void swap(double[] array, int i, int j) { double t = array[i]; array[i] = array[j]; array[j] = t; } }
1018143-musicg
src/com/musicg/math/rank/MapRankDouble.java
Java
asf20
4,479
package com.musicg.math.rank; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class MapRankShort implements MapRank{ private Map map; private boolean acsending=true; public MapRankShort(Map<?,Short> map, boolean acsending){ this.map=map; this.acsending=acsending; } public List getOrderedKeyList(int numKeys, boolean sharpLimit){ // if sharp limited, will return sharp numKeys, otherwise will return until the values not equals the exact key's value Set mapEntrySet=map.entrySet(); List keyList=new LinkedList(); // if the numKeys is larger than map size, limit it if (numKeys>map.size()){ numKeys=map.size(); } // end if the numKeys is larger than map size, limit it if (map.size()>0){ short[] array=new short[map.size()]; int count=0; // get the pass values Iterator<Entry> mapIterator=mapEntrySet.iterator(); while (mapIterator.hasNext()){ Entry entry=mapIterator.next(); array[count++]=(Short)entry.getValue(); } // end get the pass values int targetindex; if (acsending){ targetindex=numKeys; } else{ targetindex=array.length-numKeys; } short passValue=getOrderedValue(array,targetindex); // this value is the value of the numKey-th element // get the passed keys and values Map passedMap=new HashMap(); List<Short> valueList=new LinkedList<Short>(); mapIterator=mapEntrySet.iterator(); while (mapIterator.hasNext()){ Entry entry=mapIterator.next(); short value=(Short)entry.getValue(); if ((acsending && value<=passValue) || (!acsending && value>=passValue)){ passedMap.put(entry.getKey(), value); valueList.add(value); } } // end get the passed keys and values // sort the value list Short[] listArr=new Short[valueList.size()]; valueList.toArray(listArr); Arrays.sort(listArr); // end sort the value list // get the list of keys int resultCount=0; int index; if (acsending){ index=0; } else{ index=listArr.length-1; } if (!sharpLimit){ numKeys=listArr.length; } while (true){ short targetValue=(Short)listArr[index]; Iterator<Entry> passedMapIterator=passedMap.entrySet().iterator(); while(passedMapIterator.hasNext()){ Entry entry=passedMapIterator.next(); if ((Short)entry.getValue()==targetValue){ keyList.add(entry.getKey()); passedMapIterator.remove(); resultCount++; break; } } if (acsending){ index++; } else{ index--; } if (resultCount>=numKeys){ break; } } // end get the list of keys } return keyList; } private short getOrderedValue(short[] array, int index){ locate(array,0,array.length-1,index); return array[index]; } // sort the partitions by quick sort, and locate the target index private void locate(short[] array, int left, int right, int index) { int mid=(left+right)/2; //System.out.println(left+" to "+right+" ("+mid+")"); if (right==left){ //System.out.println("* "+array[targetIndex]); //result=array[targetIndex]; return; } if(left < right) { short s = array[mid]; int i = left - 1; int j = right + 1; while(true) { while(array[++i] < s) ; while(array[--j] > s) ; if(i >= j) break; swap(array, i, j); } //System.out.println("2 parts: "+left+"-"+(i-1)+" and "+(j+1)+"-"+right); if (i>index){ // the target index in the left partition //System.out.println("left partition"); locate(array, left, i-1,index); } else{ // the target index in the right partition //System.out.println("right partition"); locate(array, j+1, right,index); } } } private void swap(short[] array, int i, int j) { short t = array[i]; array[i] = array[j]; array[j] = t; } }
1018143-musicg
src/com/musicg/math/rank/MapRankShort.java
Java
asf20
4,459
/* * Copyright (C) 2011 Jacquet Wong * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.musicg.math.rank; public class ArrayRankDouble { /** * Get the index position of maximum value the given array * @param array * @return index of the max value in array */ public int getMaxValueIndex(double[] array) { int index = 0; double max = Integer.MIN_VALUE; for (int i = 0; i < array.length; i++) { if (array[i] > max) { max = array[i]; index = i; } } return index; } /** * Get the index position of minimum value in the given array * @param array * @return index of the min value in array */ public int getMinValueIndex(double[] array) { int index = 0; double min = Integer.MAX_VALUE; for (int i = 0; i < array.length; i++) { if (array[i] < min) { min = array[i]; index = i; } } return index; } /** * Get the n-th value in the array after sorted * @param array * @param n * @param ascending is ascending order or not * @return */ public double getNthOrderedValue(double[] array, int n, boolean ascending) { if (n > array.length) { n = array.length; } int targetindex; if (ascending) { targetindex = n; } else { targetindex = array.length - n; } // this value is the value of the numKey-th element double passValue = getOrderedValue(array, targetindex); return passValue; } private double getOrderedValue(double[] array, int index) { locate(array, 0, array.length - 1, index); return array[index]; } // sort the partitions by quick sort, and locate the target index private void locate(double[] array, int left, int right, int index) { int mid = (left + right) / 2; // System.out.println(left+" to "+right+" ("+mid+")"); if (right == left) { // System.out.println("* "+array[targetIndex]); // result=array[targetIndex]; return; } if (left < right) { double s = array[mid]; int i = left - 1; int j = right + 1; while (true) { while (array[++i] < s) ; while (array[--j] > s) ; if (i >= j) break; swap(array, i, j); } // System.out.println("2 parts: "+left+"-"+(i-1)+" and "+(j+1)+"-"+right); if (i > index) { // the target index in the left partition // System.out.println("left partition"); locate(array, left, i - 1, index); } else { // the target index in the right partition // System.out.println("right partition"); locate(array, j + 1, right, index); } } } private void swap(double[] array, int i, int j) { double t = array[i]; array[i] = array[j]; array[j] = t; } }
1018143-musicg
src/com/musicg/math/rank/ArrayRankDouble.java
Java
asf20
3,281
package com.musicg.math.quicksort; public class QuickSortDouble extends QuickSort{ private int[] indexes; private double[] array; public QuickSortDouble(double[] array){ this.array=array; indexes=new int[array.length]; for (int i=0; i<indexes.length; i++){ indexes[i]=i; } } public int[] getSortIndexes(){ sort(); return indexes; } private void sort() { quicksort(array, indexes, 0, indexes.length - 1); } // quicksort a[left] to a[right] private void quicksort(double[] a, int[] indexes, int left, int right) { if (right <= left) return; int i = partition(a, indexes, left, right); quicksort(a, indexes, left, i-1); quicksort(a, indexes, i+1, right); } // partition a[left] to a[right], assumes left < right private int partition(double[] a, int[] indexes, int left, int right) { int i = left - 1; int j = right; while (true) { while (a[indexes[++i]]<a[indexes[right]]); // find item on left to swap, a[right] acts as sentinel while (a[indexes[right]]<a[indexes[--j]]){ // find item on right to swap if (j == left) break; // don't go out-of-bounds } if (i >= j) break; // check if pointers cross swap(a, indexes, i, j); // swap two elements into place } swap(a, indexes, i, right); // swap with partition element return i; } // exchange a[i] and a[j] private void swap(double[] a, int[] indexes, int i, int j) { int swap = indexes[i]; indexes[i] = indexes[j]; indexes[j] = swap; } }
1018143-musicg
src/com/musicg/math/quicksort/QuickSortDouble.java
Java
asf20
1,699
package com.musicg.math.quicksort; public abstract class QuickSort{ public abstract int[] getSortIndexes(); }
1018143-musicg
src/com/musicg/math/quicksort/QuickSort.java
Java
asf20
115
package com.musicg.math.quicksort; public class QuickSortIndexPreserved { private QuickSort quickSort; public QuickSortIndexPreserved(int[] array){ quickSort=new QuickSortInteger(array); } public QuickSortIndexPreserved(double[] array){ quickSort=new QuickSortDouble(array); } public QuickSortIndexPreserved(short[] array){ quickSort=new QuickSortShort(array); } public int[] getSortIndexes(){ return quickSort.getSortIndexes(); } }
1018143-musicg
src/com/musicg/math/quicksort/QuickSortIndexPreserved.java
Java
asf20
481
package com.musicg.math.quicksort; public class QuickSortShort extends QuickSort{ private int[] indexes; private short[] array; public QuickSortShort(short[] array){ this.array=array; indexes=new int[array.length]; for (int i=0; i<indexes.length; i++){ indexes[i]=i; } } public int[] getSortIndexes(){ sort(); return indexes; } private void sort() { quicksort(array, indexes, 0, indexes.length - 1); } // quicksort a[left] to a[right] private void quicksort(short[] a, int[] indexes, int left, int right) { if (right <= left) return; int i = partition(a, indexes, left, right); quicksort(a, indexes, left, i-1); quicksort(a, indexes, i+1, right); } // partition a[left] to a[right], assumes left < right private int partition(short[] a, int[] indexes, int left, int right) { int i = left - 1; int j = right; while (true) { while (a[indexes[++i]]<a[indexes[right]]); // find item on left to swap, a[right] acts as sentinel while (a[indexes[right]]<a[indexes[--j]]){ // find item on right to swap if (j == left) break; // don't go out-of-bounds } if (i >= j) break; // check if pointers cross swap(a, indexes, i, j); // swap two elements into place } swap(a, indexes, i, right); // swap with partition element return i; } // exchange a[i] and a[j] private void swap(short[] a, int[] indexes, int i, int j) { int swap = indexes[i]; indexes[i] = indexes[j]; indexes[j] = swap; } }
1018143-musicg
src/com/musicg/math/quicksort/QuickSortShort.java
Java
asf20
1,692
package com.musicg.math.quicksort; public class QuickSortInteger extends QuickSort{ private int[] indexes; private int[] array; public QuickSortInteger(int[] array){ this.array=array; indexes=new int[array.length]; for (int i=0; i<indexes.length; i++){ indexes[i]=i; } } public int[] getSortIndexes(){ sort(); return indexes; } private void sort() { quicksort(array, indexes, 0, indexes.length - 1); } // quicksort a[left] to a[right] private void quicksort(int[] a, int[] indexes, int left, int right) { if (right <= left) return; int i = partition(a, indexes, left, right); quicksort(a, indexes, left, i-1); quicksort(a, indexes, i+1, right); } // partition a[left] to a[right], assumes left < right private int partition(int[] a, int[] indexes, int left, int right) { int i = left - 1; int j = right; while (true) { while (a[indexes[++i]]<a[indexes[right]]); // find item on left to swap, a[right] acts as sentinel while (a[indexes[right]]<a[indexes[--j]]){ // find item on right to swap if (j == left) break; // don't go out-of-bounds } if (i >= j) break; // check if pointers cross swap(a, indexes, i, j); // swap two elements into place } swap(a, indexes, i, right); // swap with partition element return i; } // exchange a[i] and a[j] private void swap(int[] a, int[] indexes, int i, int j) { int swap = indexes[i]; indexes[i] = indexes[j]; indexes[j] = swap; } }
1018143-musicg
src/com/musicg/math/quicksort/QuickSortInteger.java
Java
asf20
1,686
package com.musicg.wave; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.ArrayList; import com.musicg.api.WhistleApi; public class WaveTypeDetector { private Wave wave; public WaveTypeDetector(Wave wave) { this.wave = wave; } public double getWhistleProbability() { double probability = 0; WaveHeader wavHeader = wave.getWaveHeader(); // fft size 1024, no overlap int fftSampleSize = 1024; int fftSignalByteLength = fftSampleSize * wavHeader.getBitsPerSample() / 8; byte[] audioBytes = wave.getBytes(); ByteArrayInputStream inputStream = new ByteArrayInputStream(audioBytes); WhistleApi whistleApi = new WhistleApi(wavHeader); // read the byte signals try { int numFrames = inputStream.available() / fftSignalByteLength; byte[] bytes = new byte[fftSignalByteLength]; int checkLength = 3; int passScore = 3; ArrayList<Boolean> bufferList = new ArrayList<Boolean>(); int numWhistles = 0; int numPasses = 0; // first 10(checkLength) frames for (int frameNumber = 0; frameNumber < checkLength; frameNumber++) { inputStream.read(bytes); boolean isWhistle = whistleApi.isWhistle(bytes); bufferList.add(isWhistle); if (isWhistle) { numWhistles++; } if (numWhistles >= passScore) { numPasses++; } // System.out.println(frameNumber+": "+numWhistles); } // other frames for (int frameNumber = checkLength; frameNumber < numFrames; frameNumber++) { inputStream.read(bytes); boolean isWhistle = whistleApi.isWhistle(bytes); if (bufferList.get(0)) { numWhistles--; } bufferList.remove(0); bufferList.add(isWhistle); if (isWhistle) { numWhistles++; } if (numWhistles >= passScore) { numPasses++; } // System.out.println(frameNumber+": "+numWhistles); } probability = (double) numPasses / numFrames; } catch (IOException e) { e.printStackTrace(); } return probability; } }
1018143-musicg
src/com/musicg/wave/WaveTypeDetector.java
Java
asf20
2,068