repo
string
commit
string
message
string
diff
string
intuited/xmlearn
40335ed0e4cf673861f563b95ddaf7b85aab9840
add DocbookDumper class
diff --git a/__init__.py b/__init__.py index 55cb6e8..5085902 100755 --- a/__init__.py +++ b/__init__.py @@ -1,410 +1,426 @@ #!/usr/bin/env python """Library and CLI for learning about XML formats.""" from lxml import etree class Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. ruleset: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. outstream: a stream to which the dump will be written. For now, this function is just useful for sussing out the shape of the XML. """ # TODO: write doctest examples # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'full': {None: {'recurse': True}}} default_ruleset = 'full' from sys import stdout outstream = stdout from pprint import PrettyPrinter pformat = PrettyPrinter(indent=2).pformat # Some more defaults. maxdepth = None width = 80 # This should maybe be moved into the CLI. @classmethod def print_rulesets(cls, ruleset=None, outstream=None, format=pformat, verbose=False): """Output ruleset information. If a `ruleset` is given, that ruleset's rules are output. If no `ruleset` is given, a list of rulesets is output. The `verbose` option will cause full ruleset information to be given in the list of rulesets. `format` can be used to specify a different formatting function. """ outstream = outstream if outstream else cls.outstream if ruleset: outstream.write(format(cls.rulesets[ruleset])) else: if verbose: outstream.write(format(cls.rulesets)) else: outstream.writelines("\n".join(cls.rulesets.keys())) outstream.write("\n") def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `ruleset`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `outstream`, `maxdepth`, and `ruleset` object attributes can be overridden without modifying the object. If `ruleset` is not given, `self`'s default ruleset is used. I suspect that actually using XSLT would be a better way to do this. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) # Pull variables from kwargs or self maxdepth, outstream = (kwargs.pop(v, getattr(self, v)) for v in ('maxdepth', 'outstream')) ruleset = kwargs.pop('ruleset', getattr(self, 'ruleset', self.default_ruleset)) if isinstance(ruleset, basestring): ruleset = self.rulesets[ruleset] assert isinstance(ruleset, Mapping) def _dump(element, depth=0): for rule in ruleset.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) outstream.write(self.format_element(element, depth, **kwargs)) outstream.write("\n") if recurse: if maxdepth is None or maxdepth > depth: for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) +def clone(dict, **additions): + from copy import deepcopy + copy = deepcopy(dict) + copy.update(**additions) + return copy + +class DocbookDumper(Dumper): + """Dumper for docbook XML files.""" + + rulesets = clone(Dumper.rulesets, + book={'section': {'with_text': False}, + 'para': {'linebreak': True}, + None: {'recurse': True}}) + + default_ruleset = 'book' + def iter_unique_child_tags(bases, tags): """Iterates through unique child tags for combinations of `bases` and `tags`. `bases` and `tags` can be singular -- elements and strings -- or iterables of those respective types. """ # both elements and strings are iterable types, # so we need to check for those specific types. bases, tags = (iter((param,)) if isinstance(param, type) else iter(param) for (param, type) in ((bases, etree._Element), (tags, basestring))) from itertools import chain tag_nodes = (node for base in bases for tag in tags for node in base.iter(tag)) child_tags = (child.tag for node in tag_nodes for child in node.getchildren()) found_child_tags = set() for tag in child_tags: if tag not in found_child_tags: found_child_tags.add(tag) yield tag def iter_tag_list(bases): """List all unique tags at and under the `root` node. `bases` can be a single element or an iterable of them. """ bases = (iter((bases,)) if isinstance(bases, etree._Element) else iter(bases)) from itertools import chain tags = (node.tag for base in bases for node in base.iter() if hasattr(node, 'tag')) found_tags = set() for t in tags: if t not in found_tags: found_tags.add(t) yield t def build_tag_graph(bases): """Build a python-graph graph of the tag relationships. `bases` is an element or iterable of elements. """ from pygraph.classes.digraph import digraph g = digraph() tags = list(iter_tag_list(bases)) g.add_nodes(tags) # TODO: this is totally inefficient: # it makes more sense to do each base separately, # to avoid searching it for tags it doesn't have. # The better way is to build the set of all bases' edges. for tag in tags: for child in iter_unique_child_tags(bases, tag): g.add_edge((tag, child)) return g def write_graph(graph, filename, format='svg'): """Write a python-graph graph as an image. `format` can be any of those supported by pydot.Dot.write(). """ from pygraph.readwrite.dot import write dotdata = write(graph) from pydot import graph_from_dot_data dotgraph = graph_from_dot_data(dotdata) dotgraph.write(filename, format=format) def write_tag_graph(bases, filename, format='png'): """Build and write a graph of the tag relationships in `bases`. `bases` can be a single element or an iterable of them. """ graph = build_tag_graph(bases) write_graph(graph, filename, format=format) # TODO: refactor this as a class. def cli(args, in_, out, err, Dumper=Dumper): """Provide a command-line interface to the module functionality. Dumper: xmlearn.Dumper or subclass. Called in response to the `dump` subcommand. Note that this should be the *class*, not an instantiation of it. args: the arguments to be parsed. in_, out, err: open input/output/error files. """ from argparse import ArgumentParser, FileType, Action def instantiate_dumper(ns): kw_from_ns = ['width', 'maxdepth', 'ruleset', 'outstream'] kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if key in kw_from_ns and value is not None) return Dumper(**kwargs) def dump(ns): """Initializes a Dumper with values from the namespace `ns`. False values are filtered out. Dumps `ns.path` from the XML file `ns.infile`. """ dumper = instantiate_dumper(ns) root = etree.parse(ns.infile).getroot() return [dumper.dump(e) for e in ns.path(root)] def list_rulesets(ns): return Dumper.print_rulesets(ruleset=ns.ruleset, verbose=ns.verbose) parser = ArgumentParser() parser.add_argument('-i', '--infile', type=FileType, default=in_, help='The XML file to learn about.\n' 'Defaults to stdin.') parser.add_argument('-p', '--path', default='/*', type=etree.XPath, help='An XPath to be applied to various actions.\n' 'Defaults to the root node.') subparsers = parser.add_subparsers(title='subcommands') def build_dump_parser(subparsers): p_dump = subparsers.add_parser('dump', help='Dump xml data according to a set of rules.', description='Dump xml data according to a set of rules.') p_dump.set_defaults(action=dump, outstream=out) class ListRulesetsAction(Action): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, 'action', list_rulesets) setattr(namespace, 'ruleset', values) p_dump.add_argument('-l', '--list-rulesets', metavar='RULESET', nargs='?', action=ListRulesetsAction, help='Get a list of rulesets ' 'or information about a particular ruleset') p_dump.add_argument('-r', '--ruleset', choices=Dumper.rulesets.keys(), default=Dumper.default_ruleset, help='Which set of rules to apply.\n' 'Defaults to "{0}".' .format(Dumper.default_ruleset)) p_dump.add_argument('-d', '--maxdepth', type=int, help='How many levels to dump.') # TODO: set default width to console width # TODO: also apply the console width to the help display p_dump.add_argument('-w', '--width', type=int, help='The output width of the dump.') p_dump.add_argument('-v', '--verbose', action='store_true', help='Enable verbose ruleset list.\n' 'Only useful with `-l`.') build_dump_parser(subparsers) def build_tags_parser(subparsers): p_list = subparsers.add_parser('tags', help='Show information about tags.', description='Show information about tags.') def taglist(ns): root = etree.parse(ns.infile).getroot() itemfmt = ' {item}\n' if ns.show_element else '{item}\n' elements = ns.path(root) if ns.combine: elements = (elements,) eltfmt = lambda e: '[multiple elements]\n' else: eltfmt = lambda e: e.getroottree().getpath(e) + "\n" for element in elements: if ns.show_element: out.write(eltfmt(element)) for item in ns.tagfunc(element, *ns.tagfunc_args): out.write(itemfmt.format(item=item)) p_list.set_defaults(action=taglist, tagfunc=iter_tag_list, tagfunc_args=[]) p_list.add_argument('-e', '--show-element', action='store_true', help='Enables display of the element path.\n' 'Without this option, data from multiple matching elements ' 'will be listed in unbroken series.\n' 'This is mostly useful ' 'when the path selects multiple elements.') p_list.add_argument('-C', '--no-combine', action='store_false', dest='combine', help='Do not combine results ' 'from various path elements.\n' 'This option is only meaningful ' 'when the --path leads to multiple elements.') class ListChildrenAction(Action): """Change the tag function and set the extra argument.""" def __call__(self, parser, namespace, values, option_string=None): if values: setattr(namespace, 'tagfunc', iter_unique_child_tags) setattr(namespace, 'tagfunc_args', [values]) p_list.add_argument('-c', '--child', nargs='?', metavar='PARENT', action=ListChildrenAction, help='List all tags which appear as children of PARENT.') build_tags_parser(subparsers) def build_graph_parser(subparsers): try: from pydot import Dot formats = Dot().formats except ImportError: return p_graph = subparsers.add_parser('graph', help='Build a graph from the XML tags relationships.', description='Build a graph from the XML tags relationships.') def act(ns): extension = ns.outfile.split('.')[-1] if ns.format: if extension != ns.format: ns.outfile += '.' + ns.format else: if extension in formats: ns.format = extension root = etree.parse(ns.infile).getroot() write_tag_graph(ns.path(root), ns.outfile, ns.format) p_graph.set_defaults(action=act) p_graph.add_argument('--format', choices=formats, metavar='FORMAT', help='The format for the graph image.\n' 'It will be appended to the filename ' 'unless they already concur ' 'or -F is passed.\n' 'Choose from ' + str(formats)) p_graph.add_argument('-F', '--force-extension', help='Allow the filename extension to differ ' 'from the file format.\n' 'Without this option, the format extension ' 'will be appended to the filename.') p_graph.add_argument(dest='outfile', default=None, help='The filename for the graph image.\n' 'If no --format is given, ' 'it will be based on this name.') build_graph_parser(subparsers) namespace = parser.parse_args(args) return namespace.action(namespace) if __name__ == '__main__': from sys import argv, stdin, stdout, stderr cli(argv[1:], stdin, stdout, stderr)
intuited/xmlearn
f1d472c3c1f364b6040e3fcb94adb6870dc16bd8
revised to list base tags along with children
diff --git a/__init__.py b/__init__.py index a1112ce..55cb6e8 100755 --- a/__init__.py +++ b/__init__.py @@ -1,407 +1,410 @@ #!/usr/bin/env python """Library and CLI for learning about XML formats.""" from lxml import etree class Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. ruleset: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. outstream: a stream to which the dump will be written. For now, this function is just useful for sussing out the shape of the XML. """ # TODO: write doctest examples # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'full': {None: {'recurse': True}}} default_ruleset = 'full' from sys import stdout outstream = stdout from pprint import PrettyPrinter pformat = PrettyPrinter(indent=2).pformat # Some more defaults. maxdepth = None width = 80 # This should maybe be moved into the CLI. @classmethod def print_rulesets(cls, ruleset=None, outstream=None, format=pformat, verbose=False): """Output ruleset information. If a `ruleset` is given, that ruleset's rules are output. If no `ruleset` is given, a list of rulesets is output. The `verbose` option will cause full ruleset information to be given in the list of rulesets. `format` can be used to specify a different formatting function. """ outstream = outstream if outstream else cls.outstream if ruleset: outstream.write(format(cls.rulesets[ruleset])) else: if verbose: outstream.write(format(cls.rulesets)) else: outstream.writelines("\n".join(cls.rulesets.keys())) outstream.write("\n") def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `ruleset`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `outstream`, `maxdepth`, and `ruleset` object attributes can be overridden without modifying the object. If `ruleset` is not given, `self`'s default ruleset is used. I suspect that actually using XSLT would be a better way to do this. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) # Pull variables from kwargs or self maxdepth, outstream = (kwargs.pop(v, getattr(self, v)) for v in ('maxdepth', 'outstream')) ruleset = kwargs.pop('ruleset', getattr(self, 'ruleset', self.default_ruleset)) if isinstance(ruleset, basestring): ruleset = self.rulesets[ruleset] assert isinstance(ruleset, Mapping) def _dump(element, depth=0): for rule in ruleset.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) outstream.write(self.format_element(element, depth, **kwargs)) outstream.write("\n") if recurse: if maxdepth is None or maxdepth > depth: for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) def iter_unique_child_tags(bases, tags): """Iterates through unique child tags for combinations of `bases` and `tags`. `bases` and `tags` can be singular -- elements and strings -- or iterables of those respective types. """ # both elements and strings are iterable types, # so we need to check for those specific types. - bases, tags = (iter((p,)) if isinstance(p, t) else iter(p) - for (p, t) in ((bases, etree._Element), - (tags, basestring))) + bases, tags = (iter((param,)) if isinstance(param, type) else iter(param) + for (param, type) in ((bases, etree._Element), + (tags, basestring))) + from itertools import chain tag_nodes = (node for base in bases for tag in tags - for node in base.iterdescendants(tag)) + for node in base.iter(tag)) child_tags = (child.tag for node in tag_nodes for child in node.getchildren()) found_child_tags = set() for tag in child_tags: if tag not in found_child_tags: found_child_tags.add(tag) yield tag def iter_tag_list(bases): """List all unique tags at and under the `root` node. `bases` can be a single element or an iterable of them. """ bases = (iter((bases,)) if isinstance(bases, etree._Element) else iter(bases)) - found_tags = set() + from itertools import chain + tags = (node.tag for base in bases - for node in base.iterdescendants() + for node in base.iter() if hasattr(node, 'tag')) + found_tags = set() for t in tags: if t not in found_tags: found_tags.add(t) yield t def build_tag_graph(bases): """Build a python-graph graph of the tag relationships. `bases` is an element or iterable of elements. """ from pygraph.classes.digraph import digraph g = digraph() tags = list(iter_tag_list(bases)) g.add_nodes(tags) # TODO: this is totally inefficient: # it makes more sense to do each base separately, # to avoid searching it for tags it doesn't have. # The better way is to build the set of all bases' edges. for tag in tags: for child in iter_unique_child_tags(bases, tag): g.add_edge((tag, child)) return g def write_graph(graph, filename, format='svg'): """Write a python-graph graph as an image. `format` can be any of those supported by pydot.Dot.write(). """ from pygraph.readwrite.dot import write dotdata = write(graph) from pydot import graph_from_dot_data dotgraph = graph_from_dot_data(dotdata) dotgraph.write(filename, format=format) def write_tag_graph(bases, filename, format='png'): """Build and write a graph of the tag relationships in `bases`. `bases` can be a single element or an iterable of them. """ graph = build_tag_graph(bases) write_graph(graph, filename, format=format) # TODO: refactor this as a class. def cli(args, in_, out, err, Dumper=Dumper): """Provide a command-line interface to the module functionality. Dumper: xmlearn.Dumper or subclass. Called in response to the `dump` subcommand. Note that this should be the *class*, not an instantiation of it. args: the arguments to be parsed. in_, out, err: open input/output/error files. """ from argparse import ArgumentParser, FileType, Action def instantiate_dumper(ns): kw_from_ns = ['width', 'maxdepth', 'ruleset', 'outstream'] kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if key in kw_from_ns and value is not None) return Dumper(**kwargs) def dump(ns): """Initializes a Dumper with values from the namespace `ns`. False values are filtered out. Dumps `ns.path` from the XML file `ns.infile`. """ dumper = instantiate_dumper(ns) root = etree.parse(ns.infile).getroot() return [dumper.dump(e) for e in ns.path(root)] def list_rulesets(ns): return Dumper.print_rulesets(ruleset=ns.ruleset, verbose=ns.verbose) parser = ArgumentParser() parser.add_argument('-i', '--infile', type=FileType, default=in_, help='The XML file to learn about.\n' 'Defaults to stdin.') parser.add_argument('-p', '--path', default='/*', type=etree.XPath, help='An XPath to be applied to various actions.\n' 'Defaults to the root node.') subparsers = parser.add_subparsers(title='subcommands') def build_dump_parser(subparsers): p_dump = subparsers.add_parser('dump', help='Dump xml data according to a set of rules.', description='Dump xml data according to a set of rules.') p_dump.set_defaults(action=dump, outstream=out) class ListRulesetsAction(Action): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, 'action', list_rulesets) setattr(namespace, 'ruleset', values) p_dump.add_argument('-l', '--list-rulesets', metavar='RULESET', nargs='?', action=ListRulesetsAction, help='Get a list of rulesets ' 'or information about a particular ruleset') p_dump.add_argument('-r', '--ruleset', choices=Dumper.rulesets.keys(), default=Dumper.default_ruleset, help='Which set of rules to apply.\n' 'Defaults to "{0}".' .format(Dumper.default_ruleset)) p_dump.add_argument('-d', '--maxdepth', type=int, help='How many levels to dump.') # TODO: set default width to console width # TODO: also apply the console width to the help display p_dump.add_argument('-w', '--width', type=int, help='The output width of the dump.') p_dump.add_argument('-v', '--verbose', action='store_true', help='Enable verbose ruleset list.\n' 'Only useful with `-l`.') build_dump_parser(subparsers) def build_tags_parser(subparsers): p_list = subparsers.add_parser('tags', help='Show information about tags.', description='Show information about tags.') def taglist(ns): root = etree.parse(ns.infile).getroot() itemfmt = ' {item}\n' if ns.show_element else '{item}\n' elements = ns.path(root) if ns.combine: elements = (elements,) eltfmt = lambda e: '[multiple elements]\n' else: eltfmt = lambda e: e.getroottree().getpath(e) + "\n" for element in elements: if ns.show_element: out.write(eltfmt(element)) for item in ns.tagfunc(element, *ns.tagfunc_args): out.write(itemfmt.format(item=item)) p_list.set_defaults(action=taglist, tagfunc=iter_tag_list, tagfunc_args=[]) p_list.add_argument('-e', '--show-element', action='store_true', help='Enables display of the element path.\n' 'Without this option, data from multiple matching elements ' 'will be listed in unbroken series.\n' 'This is mostly useful ' 'when the path selects multiple elements.') p_list.add_argument('-C', '--no-combine', action='store_false', dest='combine', help='Do not combine results ' 'from various path elements.\n' 'This option is only meaningful ' 'when the --path leads to multiple elements.') class ListChildrenAction(Action): """Change the tag function and set the extra argument.""" def __call__(self, parser, namespace, values, option_string=None): if values: setattr(namespace, 'tagfunc', iter_unique_child_tags) setattr(namespace, 'tagfunc_args', [values]) p_list.add_argument('-c', '--child', nargs='?', metavar='PARENT', action=ListChildrenAction, help='List all tags which appear as children of PARENT.') build_tags_parser(subparsers) def build_graph_parser(subparsers): try: from pydot import Dot formats = Dot().formats except ImportError: return p_graph = subparsers.add_parser('graph', help='Build a graph from the XML tags relationships.', description='Build a graph from the XML tags relationships.') def act(ns): extension = ns.outfile.split('.')[-1] if ns.format: if extension != ns.format: ns.outfile += '.' + ns.format else: if extension in formats: ns.format = extension root = etree.parse(ns.infile).getroot() write_tag_graph(ns.path(root), ns.outfile, ns.format) p_graph.set_defaults(action=act) p_graph.add_argument('--format', choices=formats, metavar='FORMAT', help='The format for the graph image.\n' 'It will be appended to the filename ' 'unless they already concur ' 'or -F is passed.\n' 'Choose from ' + str(formats)) p_graph.add_argument('-F', '--force-extension', help='Allow the filename extension to differ ' 'from the file format.\n' 'Without this option, the format extension ' 'will be appended to the filename.') p_graph.add_argument(dest='outfile', default=None, help='The filename for the graph image.\n' 'If no --format is given, ' 'it will be based on this name.') build_graph_parser(subparsers) namespace = parser.parse_args(args) return namespace.action(namespace) if __name__ == '__main__': from sys import argv, stdin, stdout, stderr cli(argv[1:], stdin, stdout, stderr)
intuited/xmlearn
51b349fe1a17611001f6d86966fc616b020c80e4
add multiplexing to the graph functions and add graph subcommand to cli
diff --git a/__init__.py b/__init__.py index d86b14d..a1112ce 100755 --- a/__init__.py +++ b/__init__.py @@ -1,355 +1,407 @@ #!/usr/bin/env python """Library and CLI for learning about XML formats.""" from lxml import etree class Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. ruleset: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. outstream: a stream to which the dump will be written. For now, this function is just useful for sussing out the shape of the XML. """ # TODO: write doctest examples # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'full': {None: {'recurse': True}}} default_ruleset = 'full' from sys import stdout outstream = stdout from pprint import PrettyPrinter pformat = PrettyPrinter(indent=2).pformat # Some more defaults. maxdepth = None width = 80 # This should maybe be moved into the CLI. @classmethod def print_rulesets(cls, ruleset=None, outstream=None, format=pformat, verbose=False): """Output ruleset information. If a `ruleset` is given, that ruleset's rules are output. If no `ruleset` is given, a list of rulesets is output. The `verbose` option will cause full ruleset information to be given in the list of rulesets. `format` can be used to specify a different formatting function. """ outstream = outstream if outstream else cls.outstream if ruleset: outstream.write(format(cls.rulesets[ruleset])) else: if verbose: outstream.write(format(cls.rulesets)) else: outstream.writelines("\n".join(cls.rulesets.keys())) outstream.write("\n") def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `ruleset`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `outstream`, `maxdepth`, and `ruleset` object attributes can be overridden without modifying the object. If `ruleset` is not given, `self`'s default ruleset is used. I suspect that actually using XSLT would be a better way to do this. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) # Pull variables from kwargs or self maxdepth, outstream = (kwargs.pop(v, getattr(self, v)) for v in ('maxdepth', 'outstream')) ruleset = kwargs.pop('ruleset', getattr(self, 'ruleset', self.default_ruleset)) if isinstance(ruleset, basestring): ruleset = self.rulesets[ruleset] assert isinstance(ruleset, Mapping) def _dump(element, depth=0): for rule in ruleset.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) outstream.write(self.format_element(element, depth, **kwargs)) outstream.write("\n") if recurse: if maxdepth is None or maxdepth > depth: for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) def iter_unique_child_tags(bases, tags): """Iterates through unique child tags for combinations of `bases` and `tags`. `bases` and `tags` can be singular -- elements and strings -- or iterables of those respective types. """ # both elements and strings are iterable types, # so we need to check for those specific types. bases, tags = (iter((p,)) if isinstance(p, t) else iter(p) for (p, t) in ((bases, etree._Element), (tags, basestring))) tag_nodes = (node for base in bases for tag in tags for node in base.iterdescendants(tag)) child_tags = (child.tag for node in tag_nodes for child in node.getchildren()) found_child_tags = set() for tag in child_tags: if tag not in found_child_tags: found_child_tags.add(tag) yield tag def iter_tag_list(bases): """List all unique tags at and under the `root` node. `bases` can be a single element or an iterable of them. """ bases = (iter((bases,)) if isinstance(bases, etree._Element) else iter(bases)) found_tags = set() tags = (node.tag for base in bases for node in base.iterdescendants() if hasattr(node, 'tag')) for t in tags: if t not in found_tags: found_tags.add(t) yield t -def build_tag_graph(root): - """Build a python-graph graph of the tag relationships.""" +def build_tag_graph(bases): + """Build a python-graph graph of the tag relationships. + + `bases` is an element or iterable of elements. + """ from pygraph.classes.digraph import digraph g = digraph() - tags = list(iter_tag_list(root)) + tags = list(iter_tag_list(bases)) g.add_nodes(tags) - for parent in tags: - for child in iter_unique_child_tags(root, parent): - g.add_edge((parent, child)) + # TODO: this is totally inefficient: + # it makes more sense to do each base separately, + # to avoid searching it for tags it doesn't have. + # The better way is to build the set of all bases' edges. + for tag in tags: + for child in iter_unique_child_tags(bases, tag): + g.add_edge((tag, child)) return g -def write_graph(graph, filename, format='png'): +def write_graph(graph, filename, format='svg'): """Write a python-graph graph as an image. `format` can be any of those supported by pydot.Dot.write(). """ from pygraph.readwrite.dot import write dotdata = write(graph) from pydot import graph_from_dot_data dotgraph = graph_from_dot_data(dotdata) dotgraph.write(filename, format=format) -def write_tag_graph(root, filename, format='png'): - graph = build_tag_graph(root) +def write_tag_graph(bases, filename, format='png'): + """Build and write a graph of the tag relationships in `bases`. + + `bases` can be a single element or an iterable of them. + """ + graph = build_tag_graph(bases) write_graph(graph, filename, format=format) # TODO: refactor this as a class. def cli(args, in_, out, err, Dumper=Dumper): """Provide a command-line interface to the module functionality. Dumper: xmlearn.Dumper or subclass. Called in response to the `dump` subcommand. Note that this should be the *class*, not an instantiation of it. args: the arguments to be parsed. in_, out, err: open input/output/error files. """ from argparse import ArgumentParser, FileType, Action def instantiate_dumper(ns): kw_from_ns = ['width', 'maxdepth', 'ruleset', 'outstream'] kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if key in kw_from_ns and value is not None) return Dumper(**kwargs) def dump(ns): """Initializes a Dumper with values from the namespace `ns`. False values are filtered out. Dumps `ns.path` from the XML file `ns.infile`. """ dumper = instantiate_dumper(ns) root = etree.parse(ns.infile).getroot() return [dumper.dump(e) for e in ns.path(root)] def list_rulesets(ns): return Dumper.print_rulesets(ruleset=ns.ruleset, verbose=ns.verbose) parser = ArgumentParser() parser.add_argument('-i', '--infile', type=FileType, default=in_, help='The XML file to learn about.\n' 'Defaults to stdin.') parser.add_argument('-p', '--path', default='/*', type=etree.XPath, help='An XPath to be applied to various actions.\n' 'Defaults to the root node.') subparsers = parser.add_subparsers(title='subcommands') def build_dump_parser(subparsers): p_dump = subparsers.add_parser('dump', help='Dump xml data according to a set of rules.', description='Dump xml data according to a set of rules.') p_dump.set_defaults(action=dump, outstream=out) class ListRulesetsAction(Action): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, 'action', list_rulesets) setattr(namespace, 'ruleset', values) p_dump.add_argument('-l', '--list-rulesets', metavar='RULESET', nargs='?', action=ListRulesetsAction, help='Get a list of rulesets ' 'or information about a particular ruleset') p_dump.add_argument('-r', '--ruleset', choices=Dumper.rulesets.keys(), default=Dumper.default_ruleset, help='Which set of rules to apply.\n' 'Defaults to "{0}".' .format(Dumper.default_ruleset)) p_dump.add_argument('-d', '--maxdepth', type=int, help='How many levels to dump.') # TODO: set default width to console width # TODO: also apply the console width to the help display p_dump.add_argument('-w', '--width', type=int, help='The output width of the dump.') p_dump.add_argument('-v', '--verbose', action='store_true', help='Enable verbose ruleset list.\n' 'Only useful with `-l`.') build_dump_parser(subparsers) def build_tags_parser(subparsers): p_list = subparsers.add_parser('tags', help='Show information about tags.', description='Show information about tags.') def taglist(ns): root = etree.parse(ns.infile).getroot() itemfmt = ' {item}\n' if ns.show_element else '{item}\n' elements = ns.path(root) if ns.combine: elements = (elements,) eltfmt = lambda e: '[multiple elements]\n' else: eltfmt = lambda e: e.getroottree().getpath(e) + "\n" for element in elements: if ns.show_element: out.write(eltfmt(element)) for item in ns.tagfunc(element, *ns.tagfunc_args): out.write(itemfmt.format(item=item)) p_list.set_defaults(action=taglist, tagfunc=iter_tag_list, tagfunc_args=[]) p_list.add_argument('-e', '--show-element', action='store_true', help='Enables display of the element path.\n' 'Without this option, data from multiple matching elements ' 'will be listed in unbroken series.\n' 'This is mostly useful ' 'when the path selects multiple elements.') p_list.add_argument('-C', '--no-combine', action='store_false', dest='combine', help='Do not combine results ' 'from various path elements.\n' 'This option is only meaningful ' 'when the --path leads to multiple elements.') class ListChildrenAction(Action): """Change the tag function and set the extra argument.""" def __call__(self, parser, namespace, values, option_string=None): if values: setattr(namespace, 'tagfunc', iter_unique_child_tags) setattr(namespace, 'tagfunc_args', [values]) p_list.add_argument('-c', '--child', nargs='?', metavar='PARENT', action=ListChildrenAction, help='List all tags which appear as children of PARENT.') build_tags_parser(subparsers) + def build_graph_parser(subparsers): + try: + from pydot import Dot + formats = Dot().formats + except ImportError: + return + + p_graph = subparsers.add_parser('graph', + help='Build a graph from the XML tags relationships.', + description='Build a graph from the XML tags relationships.') + + def act(ns): + extension = ns.outfile.split('.')[-1] + if ns.format: + if extension != ns.format: + ns.outfile += '.' + ns.format + else: + if extension in formats: + ns.format = extension + + root = etree.parse(ns.infile).getroot() + write_tag_graph(ns.path(root), ns.outfile, ns.format) + + p_graph.set_defaults(action=act) + p_graph.add_argument('--format', choices=formats, metavar='FORMAT', + help='The format for the graph image.\n' + 'It will be appended to the filename ' + 'unless they already concur ' + 'or -F is passed.\n' + 'Choose from ' + str(formats)) + p_graph.add_argument('-F', '--force-extension', + help='Allow the filename extension to differ ' + 'from the file format.\n' + 'Without this option, the format extension ' + 'will be appended to the filename.') + p_graph.add_argument(dest='outfile', default=None, + help='The filename for the graph image.\n' + 'If no --format is given, ' + 'it will be based on this name.') + build_graph_parser(subparsers) + namespace = parser.parse_args(args) return namespace.action(namespace) if __name__ == '__main__': from sys import argv, stdin, stdout, stderr cli(argv[1:], stdin, stdout, stderr)
intuited/xmlearn
84ef8cb325e0e2838a98fa5c7417756e0b305114
remove obsolete TODO
diff --git a/__init__.py b/__init__.py index 1e7a8b4..d86b14d 100755 --- a/__init__.py +++ b/__init__.py @@ -1,356 +1,355 @@ #!/usr/bin/env python """Library and CLI for learning about XML formats.""" from lxml import etree class Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. ruleset: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. outstream: a stream to which the dump will be written. For now, this function is just useful for sussing out the shape of the XML. """ # TODO: write doctest examples # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'full': {None: {'recurse': True}}} default_ruleset = 'full' from sys import stdout outstream = stdout from pprint import PrettyPrinter pformat = PrettyPrinter(indent=2).pformat # Some more defaults. maxdepth = None width = 80 # This should maybe be moved into the CLI. @classmethod def print_rulesets(cls, ruleset=None, outstream=None, format=pformat, verbose=False): """Output ruleset information. If a `ruleset` is given, that ruleset's rules are output. If no `ruleset` is given, a list of rulesets is output. The `verbose` option will cause full ruleset information to be given in the list of rulesets. `format` can be used to specify a different formatting function. """ outstream = outstream if outstream else cls.outstream if ruleset: outstream.write(format(cls.rulesets[ruleset])) else: if verbose: outstream.write(format(cls.rulesets)) else: outstream.writelines("\n".join(cls.rulesets.keys())) outstream.write("\n") def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `ruleset`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `outstream`, `maxdepth`, and `ruleset` object attributes can be overridden without modifying the object. If `ruleset` is not given, `self`'s default ruleset is used. I suspect that actually using XSLT would be a better way to do this. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) # Pull variables from kwargs or self maxdepth, outstream = (kwargs.pop(v, getattr(self, v)) for v in ('maxdepth', 'outstream')) ruleset = kwargs.pop('ruleset', getattr(self, 'ruleset', self.default_ruleset)) if isinstance(ruleset, basestring): ruleset = self.rulesets[ruleset] assert isinstance(ruleset, Mapping) def _dump(element, depth=0): for rule in ruleset.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) outstream.write(self.format_element(element, depth, **kwargs)) outstream.write("\n") if recurse: if maxdepth is None or maxdepth > depth: for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) def iter_unique_child_tags(bases, tags): """Iterates through unique child tags for combinations of `bases` and `tags`. `bases` and `tags` can be singular -- elements and strings -- or iterables of those respective types. """ # both elements and strings are iterable types, # so we need to check for those specific types. bases, tags = (iter((p,)) if isinstance(p, t) else iter(p) for (p, t) in ((bases, etree._Element), (tags, basestring))) tag_nodes = (node for base in bases for tag in tags for node in base.iterdescendants(tag)) child_tags = (child.tag for node in tag_nodes for child in node.getchildren()) found_child_tags = set() for tag in child_tags: if tag not in found_child_tags: found_child_tags.add(tag) yield tag def iter_tag_list(bases): """List all unique tags at and under the `root` node. `bases` can be a single element or an iterable of them. """ bases = (iter((bases,)) if isinstance(bases, etree._Element) else iter(bases)) found_tags = set() tags = (node.tag for base in bases for node in base.iterdescendants() if hasattr(node, 'tag')) for t in tags: if t not in found_tags: found_tags.add(t) yield t def build_tag_graph(root): """Build a python-graph graph of the tag relationships.""" from pygraph.classes.digraph import digraph g = digraph() tags = list(iter_tag_list(root)) g.add_nodes(tags) for parent in tags: for child in iter_unique_child_tags(root, parent): g.add_edge((parent, child)) return g def write_graph(graph, filename, format='png'): """Write a python-graph graph as an image. `format` can be any of those supported by pydot.Dot.write(). """ from pygraph.readwrite.dot import write dotdata = write(graph) from pydot import graph_from_dot_data dotgraph = graph_from_dot_data(dotdata) dotgraph.write(filename, format=format) def write_tag_graph(root, filename, format='png'): graph = build_tag_graph(root) write_graph(graph, filename, format=format) # TODO: refactor this as a class. -# TODO: make the dump command's `path` option a general one. def cli(args, in_, out, err, Dumper=Dumper): """Provide a command-line interface to the module functionality. Dumper: xmlearn.Dumper or subclass. Called in response to the `dump` subcommand. Note that this should be the *class*, not an instantiation of it. args: the arguments to be parsed. in_, out, err: open input/output/error files. """ from argparse import ArgumentParser, FileType, Action def instantiate_dumper(ns): kw_from_ns = ['width', 'maxdepth', 'ruleset', 'outstream'] kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if key in kw_from_ns and value is not None) return Dumper(**kwargs) def dump(ns): """Initializes a Dumper with values from the namespace `ns`. False values are filtered out. Dumps `ns.path` from the XML file `ns.infile`. """ dumper = instantiate_dumper(ns) root = etree.parse(ns.infile).getroot() return [dumper.dump(e) for e in ns.path(root)] def list_rulesets(ns): return Dumper.print_rulesets(ruleset=ns.ruleset, verbose=ns.verbose) parser = ArgumentParser() parser.add_argument('-i', '--infile', type=FileType, default=in_, help='The XML file to learn about.\n' 'Defaults to stdin.') parser.add_argument('-p', '--path', default='/*', type=etree.XPath, help='An XPath to be applied to various actions.\n' 'Defaults to the root node.') subparsers = parser.add_subparsers(title='subcommands') def build_dump_parser(subparsers): p_dump = subparsers.add_parser('dump', help='Dump xml data according to a set of rules.', description='Dump xml data according to a set of rules.') p_dump.set_defaults(action=dump, outstream=out) class ListRulesetsAction(Action): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, 'action', list_rulesets) setattr(namespace, 'ruleset', values) p_dump.add_argument('-l', '--list-rulesets', metavar='RULESET', nargs='?', action=ListRulesetsAction, help='Get a list of rulesets ' 'or information about a particular ruleset') p_dump.add_argument('-r', '--ruleset', choices=Dumper.rulesets.keys(), default=Dumper.default_ruleset, help='Which set of rules to apply.\n' 'Defaults to "{0}".' .format(Dumper.default_ruleset)) p_dump.add_argument('-d', '--maxdepth', type=int, help='How many levels to dump.') # TODO: set default width to console width # TODO: also apply the console width to the help display p_dump.add_argument('-w', '--width', type=int, help='The output width of the dump.') p_dump.add_argument('-v', '--verbose', action='store_true', help='Enable verbose ruleset list.\n' 'Only useful with `-l`.') build_dump_parser(subparsers) def build_tags_parser(subparsers): p_list = subparsers.add_parser('tags', help='Show information about tags.', description='Show information about tags.') def taglist(ns): root = etree.parse(ns.infile).getroot() itemfmt = ' {item}\n' if ns.show_element else '{item}\n' elements = ns.path(root) if ns.combine: elements = (elements,) eltfmt = lambda e: '[multiple elements]\n' else: eltfmt = lambda e: e.getroottree().getpath(e) + "\n" for element in elements: if ns.show_element: out.write(eltfmt(element)) for item in ns.tagfunc(element, *ns.tagfunc_args): out.write(itemfmt.format(item=item)) p_list.set_defaults(action=taglist, tagfunc=iter_tag_list, tagfunc_args=[]) p_list.add_argument('-e', '--show-element', action='store_true', help='Enables display of the element path.\n' 'Without this option, data from multiple matching elements ' 'will be listed in unbroken series.\n' 'This is mostly useful ' 'when the path selects multiple elements.') p_list.add_argument('-C', '--no-combine', action='store_false', dest='combine', help='Do not combine results ' 'from various path elements.\n' 'This option is only meaningful ' 'when the --path leads to multiple elements.') class ListChildrenAction(Action): """Change the tag function and set the extra argument.""" def __call__(self, parser, namespace, values, option_string=None): if values: setattr(namespace, 'tagfunc', iter_unique_child_tags) setattr(namespace, 'tagfunc_args', [values]) p_list.add_argument('-c', '--child', nargs='?', metavar='PARENT', action=ListChildrenAction, help='List all tags which appear as children of PARENT.') build_tags_parser(subparsers) namespace = parser.parse_args(args) return namespace.action(namespace) if __name__ == '__main__': from sys import argv, stdin, stdout, stderr cli(argv[1:], stdin, stdout, stderr)
intuited/xmlearn
48d93418d2622a99b9e8cf3b60b4ddf23eeaed20
add the --no-combine CLI option and logic
diff --git a/__init__.py b/__init__.py index 0bfb9e8..1e7a8b4 100755 --- a/__init__.py +++ b/__init__.py @@ -1,344 +1,356 @@ #!/usr/bin/env python """Library and CLI for learning about XML formats.""" from lxml import etree class Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. ruleset: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. outstream: a stream to which the dump will be written. For now, this function is just useful for sussing out the shape of the XML. """ # TODO: write doctest examples # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'full': {None: {'recurse': True}}} default_ruleset = 'full' from sys import stdout outstream = stdout from pprint import PrettyPrinter pformat = PrettyPrinter(indent=2).pformat # Some more defaults. maxdepth = None width = 80 # This should maybe be moved into the CLI. @classmethod def print_rulesets(cls, ruleset=None, outstream=None, format=pformat, verbose=False): """Output ruleset information. If a `ruleset` is given, that ruleset's rules are output. If no `ruleset` is given, a list of rulesets is output. The `verbose` option will cause full ruleset information to be given in the list of rulesets. `format` can be used to specify a different formatting function. """ outstream = outstream if outstream else cls.outstream if ruleset: outstream.write(format(cls.rulesets[ruleset])) else: if verbose: outstream.write(format(cls.rulesets)) else: outstream.writelines("\n".join(cls.rulesets.keys())) outstream.write("\n") def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `ruleset`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `outstream`, `maxdepth`, and `ruleset` object attributes can be overridden without modifying the object. If `ruleset` is not given, `self`'s default ruleset is used. I suspect that actually using XSLT would be a better way to do this. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) # Pull variables from kwargs or self maxdepth, outstream = (kwargs.pop(v, getattr(self, v)) for v in ('maxdepth', 'outstream')) ruleset = kwargs.pop('ruleset', getattr(self, 'ruleset', self.default_ruleset)) if isinstance(ruleset, basestring): ruleset = self.rulesets[ruleset] assert isinstance(ruleset, Mapping) def _dump(element, depth=0): for rule in ruleset.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) outstream.write(self.format_element(element, depth, **kwargs)) outstream.write("\n") if recurse: if maxdepth is None or maxdepth > depth: for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) def iter_unique_child_tags(bases, tags): """Iterates through unique child tags for combinations of `bases` and `tags`. `bases` and `tags` can be singular -- elements and strings -- or iterables of those respective types. """ # both elements and strings are iterable types, # so we need to check for those specific types. bases, tags = (iter((p,)) if isinstance(p, t) else iter(p) for (p, t) in ((bases, etree._Element), (tags, basestring))) tag_nodes = (node for base in bases for tag in tags for node in base.iterdescendants(tag)) child_tags = (child.tag for node in tag_nodes for child in node.getchildren()) found_child_tags = set() for tag in child_tags: if tag not in found_child_tags: found_child_tags.add(tag) yield tag def iter_tag_list(bases): """List all unique tags at and under the `root` node. `bases` can be a single element or an iterable of them. """ bases = (iter((bases,)) if isinstance(bases, etree._Element) else iter(bases)) found_tags = set() tags = (node.tag for base in bases for node in base.iterdescendants() if hasattr(node, 'tag')) for t in tags: if t not in found_tags: found_tags.add(t) yield t def build_tag_graph(root): """Build a python-graph graph of the tag relationships.""" from pygraph.classes.digraph import digraph g = digraph() tags = list(iter_tag_list(root)) g.add_nodes(tags) for parent in tags: for child in iter_unique_child_tags(root, parent): g.add_edge((parent, child)) return g def write_graph(graph, filename, format='png'): """Write a python-graph graph as an image. `format` can be any of those supported by pydot.Dot.write(). """ from pygraph.readwrite.dot import write dotdata = write(graph) from pydot import graph_from_dot_data dotgraph = graph_from_dot_data(dotdata) dotgraph.write(filename, format=format) def write_tag_graph(root, filename, format='png'): graph = build_tag_graph(root) write_graph(graph, filename, format=format) # TODO: refactor this as a class. # TODO: make the dump command's `path` option a general one. def cli(args, in_, out, err, Dumper=Dumper): """Provide a command-line interface to the module functionality. Dumper: xmlearn.Dumper or subclass. Called in response to the `dump` subcommand. Note that this should be the *class*, not an instantiation of it. args: the arguments to be parsed. in_, out, err: open input/output/error files. """ from argparse import ArgumentParser, FileType, Action def instantiate_dumper(ns): kw_from_ns = ['width', 'maxdepth', 'ruleset', 'outstream'] kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if key in kw_from_ns and value is not None) return Dumper(**kwargs) def dump(ns): """Initializes a Dumper with values from the namespace `ns`. False values are filtered out. Dumps `ns.path` from the XML file `ns.infile`. """ dumper = instantiate_dumper(ns) root = etree.parse(ns.infile).getroot() return [dumper.dump(e) for e in ns.path(root)] def list_rulesets(ns): return Dumper.print_rulesets(ruleset=ns.ruleset, verbose=ns.verbose) parser = ArgumentParser() parser.add_argument('-i', '--infile', type=FileType, default=in_, help='The XML file to learn about.\n' 'Defaults to stdin.') parser.add_argument('-p', '--path', default='/*', type=etree.XPath, help='An XPath to be applied to various actions.\n' 'Defaults to the root node.') subparsers = parser.add_subparsers(title='subcommands') def build_dump_parser(subparsers): p_dump = subparsers.add_parser('dump', help='Dump xml data according to a set of rules.', description='Dump xml data according to a set of rules.') p_dump.set_defaults(action=dump, outstream=out) class ListRulesetsAction(Action): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, 'action', list_rulesets) setattr(namespace, 'ruleset', values) p_dump.add_argument('-l', '--list-rulesets', metavar='RULESET', nargs='?', action=ListRulesetsAction, help='Get a list of rulesets ' 'or information about a particular ruleset') p_dump.add_argument('-r', '--ruleset', choices=Dumper.rulesets.keys(), default=Dumper.default_ruleset, help='Which set of rules to apply.\n' 'Defaults to "{0}".' .format(Dumper.default_ruleset)) p_dump.add_argument('-d', '--maxdepth', type=int, help='How many levels to dump.') # TODO: set default width to console width # TODO: also apply the console width to the help display p_dump.add_argument('-w', '--width', type=int, help='The output width of the dump.') p_dump.add_argument('-v', '--verbose', action='store_true', help='Enable verbose ruleset list.\n' 'Only useful with `-l`.') build_dump_parser(subparsers) def build_tags_parser(subparsers): p_list = subparsers.add_parser('tags', help='Show information about tags.', description='Show information about tags.') def taglist(ns): root = etree.parse(ns.infile).getroot() itemfmt = ' {item}\n' if ns.show_element else '{item}\n' - for element in ns.path(root): + elements = ns.path(root) + if ns.combine: + elements = (elements,) + eltfmt = lambda e: '[multiple elements]\n' + else: + eltfmt = lambda e: e.getroottree().getpath(e) + "\n" + for element in elements: if ns.show_element: - out.write(element.getroottree().getpath(element) + "\n") + out.write(eltfmt(element)) for item in ns.tagfunc(element, *ns.tagfunc_args): out.write(itemfmt.format(item=item)) p_list.set_defaults(action=taglist, tagfunc=iter_tag_list, tagfunc_args=[]) p_list.add_argument('-e', '--show-element', action='store_true', help='Enables display of the element path.\n' 'Without this option, data from multiple matching elements ' 'will be listed in unbroken series.\n' 'This is mostly useful ' 'when the path selects multiple elements.') + p_list.add_argument('-C', '--no-combine', action='store_false', + dest='combine', + help='Do not combine results ' + 'from various path elements.\n' + 'This option is only meaningful ' + 'when the --path leads to multiple elements.') class ListChildrenAction(Action): """Change the tag function and set the extra argument.""" def __call__(self, parser, namespace, values, option_string=None): if values: setattr(namespace, 'tagfunc', iter_unique_child_tags) setattr(namespace, 'tagfunc_args', [values]) p_list.add_argument('-c', '--child', nargs='?', metavar='PARENT', action=ListChildrenAction, help='List all tags which appear as children of PARENT.') build_tags_parser(subparsers) namespace = parser.parse_args(args) return namespace.action(namespace) if __name__ == '__main__': from sys import argv, stdin, stdout, stderr cli(argv[1:], stdin, stdout, stderr)
intuited/xmlearn
500b16fd9fee9dc3aed139a4752e82379b610a9b
rework tag iterators to accept iterable as well as singular arguments
diff --git a/__init__.py b/__init__.py index dab9241..0bfb9e8 100755 --- a/__init__.py +++ b/__init__.py @@ -1,326 +1,344 @@ #!/usr/bin/env python """Library and CLI for learning about XML formats.""" from lxml import etree class Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. ruleset: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. outstream: a stream to which the dump will be written. For now, this function is just useful for sussing out the shape of the XML. """ # TODO: write doctest examples # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'full': {None: {'recurse': True}}} default_ruleset = 'full' from sys import stdout outstream = stdout from pprint import PrettyPrinter pformat = PrettyPrinter(indent=2).pformat # Some more defaults. maxdepth = None width = 80 # This should maybe be moved into the CLI. @classmethod def print_rulesets(cls, ruleset=None, outstream=None, format=pformat, verbose=False): """Output ruleset information. If a `ruleset` is given, that ruleset's rules are output. If no `ruleset` is given, a list of rulesets is output. The `verbose` option will cause full ruleset information to be given in the list of rulesets. `format` can be used to specify a different formatting function. """ outstream = outstream if outstream else cls.outstream if ruleset: outstream.write(format(cls.rulesets[ruleset])) else: if verbose: outstream.write(format(cls.rulesets)) else: outstream.writelines("\n".join(cls.rulesets.keys())) outstream.write("\n") def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `ruleset`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `outstream`, `maxdepth`, and `ruleset` object attributes can be overridden without modifying the object. If `ruleset` is not given, `self`'s default ruleset is used. I suspect that actually using XSLT would be a better way to do this. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) # Pull variables from kwargs or self maxdepth, outstream = (kwargs.pop(v, getattr(self, v)) for v in ('maxdepth', 'outstream')) ruleset = kwargs.pop('ruleset', getattr(self, 'ruleset', self.default_ruleset)) if isinstance(ruleset, basestring): ruleset = self.rulesets[ruleset] assert isinstance(ruleset, Mapping) def _dump(element, depth=0): for rule in ruleset.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) outstream.write(self.format_element(element, depth, **kwargs)) outstream.write("\n") if recurse: if maxdepth is None or maxdepth > depth: for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) -def iter_unique_child_tags(root, tag): - """Iterates through unique child tags for all instances of `tag`. +def iter_unique_child_tags(bases, tags): + """Iterates through unique child tags for combinations of + `bases` and `tags`. - Iteration starts at `root`. + `bases` and `tags` can be singular -- elements and strings -- + or iterables of those respective types. """ + # both elements and strings are iterable types, + # so we need to check for those specific types. + bases, tags = (iter((p,)) if isinstance(p, t) else iter(p) + for (p, t) in ((bases, etree._Element), + (tags, basestring))) + + tag_nodes = (node for base in bases for tag in tags + for node in base.iterdescendants(tag)) + + child_tags = (child.tag for node in tag_nodes + for child in node.getchildren()) + found_child_tags = set() - instances = root.iterdescendants(tag) - from itertools import chain - child_nodes = chain.from_iterable(i.getchildren() for i in instances) - child_tags = (n.tag for n in child_nodes) - for t in child_tags: - if t not in found_child_tags: - found_child_tags.add(t) - yield t + for tag in child_tags: + if tag not in found_child_tags: + found_child_tags.add(tag) + yield tag + +def iter_tag_list(bases): + """List all unique tags at and under the `root` node. + + `bases` can be a single element or an iterable of them. + """ + bases = (iter((bases,)) if isinstance(bases, etree._Element) + else iter(bases)) -def iter_tag_list(root): - """List all unique tags at and under the `root` node.""" found_tags = set() - tags = (n.tag for n in root.iterdescendants() if hasattr(n, 'tag')) + tags = (node.tag for base in bases + for node in base.iterdescendants() + if hasattr(node, 'tag')) for t in tags: if t not in found_tags: found_tags.add(t) yield t def build_tag_graph(root): """Build a python-graph graph of the tag relationships.""" from pygraph.classes.digraph import digraph g = digraph() tags = list(iter_tag_list(root)) g.add_nodes(tags) for parent in tags: for child in iter_unique_child_tags(root, parent): g.add_edge((parent, child)) return g def write_graph(graph, filename, format='png'): """Write a python-graph graph as an image. `format` can be any of those supported by pydot.Dot.write(). """ from pygraph.readwrite.dot import write dotdata = write(graph) from pydot import graph_from_dot_data dotgraph = graph_from_dot_data(dotdata) dotgraph.write(filename, format=format) def write_tag_graph(root, filename, format='png'): graph = build_tag_graph(root) write_graph(graph, filename, format=format) # TODO: refactor this as a class. # TODO: make the dump command's `path` option a general one. def cli(args, in_, out, err, Dumper=Dumper): """Provide a command-line interface to the module functionality. Dumper: xmlearn.Dumper or subclass. Called in response to the `dump` subcommand. Note that this should be the *class*, not an instantiation of it. args: the arguments to be parsed. in_, out, err: open input/output/error files. """ from argparse import ArgumentParser, FileType, Action def instantiate_dumper(ns): kw_from_ns = ['width', 'maxdepth', 'ruleset', 'outstream'] kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if key in kw_from_ns and value is not None) return Dumper(**kwargs) def dump(ns): """Initializes a Dumper with values from the namespace `ns`. False values are filtered out. Dumps `ns.path` from the XML file `ns.infile`. """ dumper = instantiate_dumper(ns) root = etree.parse(ns.infile).getroot() return [dumper.dump(e) for e in ns.path(root)] def list_rulesets(ns): return Dumper.print_rulesets(ruleset=ns.ruleset, verbose=ns.verbose) parser = ArgumentParser() parser.add_argument('-i', '--infile', type=FileType, default=in_, help='The XML file to learn about.\n' 'Defaults to stdin.') parser.add_argument('-p', '--path', default='/*', type=etree.XPath, help='An XPath to be applied to various actions.\n' 'Defaults to the root node.') subparsers = parser.add_subparsers(title='subcommands') def build_dump_parser(subparsers): p_dump = subparsers.add_parser('dump', help='Dump xml data according to a set of rules.', description='Dump xml data according to a set of rules.') p_dump.set_defaults(action=dump, outstream=out) class ListRulesetsAction(Action): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, 'action', list_rulesets) setattr(namespace, 'ruleset', values) p_dump.add_argument('-l', '--list-rulesets', metavar='RULESET', nargs='?', action=ListRulesetsAction, help='Get a list of rulesets ' 'or information about a particular ruleset') p_dump.add_argument('-r', '--ruleset', choices=Dumper.rulesets.keys(), default=Dumper.default_ruleset, help='Which set of rules to apply.\n' 'Defaults to "{0}".' .format(Dumper.default_ruleset)) p_dump.add_argument('-d', '--maxdepth', type=int, help='How many levels to dump.') # TODO: set default width to console width # TODO: also apply the console width to the help display p_dump.add_argument('-w', '--width', type=int, help='The output width of the dump.') p_dump.add_argument('-v', '--verbose', action='store_true', help='Enable verbose ruleset list.\n' 'Only useful with `-l`.') build_dump_parser(subparsers) def build_tags_parser(subparsers): p_list = subparsers.add_parser('tags', help='Show information about tags.', description='Show information about tags.') def taglist(ns): root = etree.parse(ns.infile).getroot() itemfmt = ' {item}\n' if ns.show_element else '{item}\n' for element in ns.path(root): if ns.show_element: out.write(element.getroottree().getpath(element) + "\n") for item in ns.tagfunc(element, *ns.tagfunc_args): out.write(itemfmt.format(item=item)) p_list.set_defaults(action=taglist, tagfunc=iter_tag_list, tagfunc_args=[]) p_list.add_argument('-e', '--show-element', action='store_true', help='Enables display of the element path.\n' 'Without this option, data from multiple matching elements ' 'will be listed in unbroken series.\n' 'This is mostly useful ' 'when the path selects multiple elements.') class ListChildrenAction(Action): """Change the tag function and set the extra argument.""" def __call__(self, parser, namespace, values, option_string=None): if values: setattr(namespace, 'tagfunc', iter_unique_child_tags) setattr(namespace, 'tagfunc_args', [values]) p_list.add_argument('-c', '--child', nargs='?', metavar='PARENT', action=ListChildrenAction, help='List all tags which appear as children of PARENT.') build_tags_parser(subparsers) namespace = parser.parse_args(args) return namespace.action(namespace) if __name__ == '__main__': from sys import argv, stdin, stdout, stderr cli(argv[1:], stdin, stdout, stderr)
intuited/xmlearn
1288c56645f358bd522ac25a493d7a5a903fdfcc
frig with spacing
diff --git a/__init__.py b/__init__.py index 036cf5a..dab9241 100755 --- a/__init__.py +++ b/__init__.py @@ -1,328 +1,326 @@ #!/usr/bin/env python """Library and CLI for learning about XML formats.""" from lxml import etree class Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. ruleset: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. outstream: a stream to which the dump will be written. For now, this function is just useful for sussing out the shape of the XML. """ # TODO: write doctest examples # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'full': {None: {'recurse': True}}} default_ruleset = 'full' from sys import stdout outstream = stdout from pprint import PrettyPrinter pformat = PrettyPrinter(indent=2).pformat # Some more defaults. maxdepth = None width = 80 # This should maybe be moved into the CLI. @classmethod def print_rulesets(cls, ruleset=None, outstream=None, format=pformat, verbose=False): """Output ruleset information. If a `ruleset` is given, that ruleset's rules are output. If no `ruleset` is given, a list of rulesets is output. The `verbose` option will cause full ruleset information to be given in the list of rulesets. `format` can be used to specify a different formatting function. """ outstream = outstream if outstream else cls.outstream if ruleset: outstream.write(format(cls.rulesets[ruleset])) else: if verbose: outstream.write(format(cls.rulesets)) else: outstream.writelines("\n".join(cls.rulesets.keys())) outstream.write("\n") def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `ruleset`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `outstream`, `maxdepth`, and `ruleset` object attributes can be overridden without modifying the object. If `ruleset` is not given, `self`'s default ruleset is used. I suspect that actually using XSLT would be a better way to do this. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) # Pull variables from kwargs or self maxdepth, outstream = (kwargs.pop(v, getattr(self, v)) for v in ('maxdepth', 'outstream')) ruleset = kwargs.pop('ruleset', getattr(self, 'ruleset', self.default_ruleset)) if isinstance(ruleset, basestring): ruleset = self.rulesets[ruleset] assert isinstance(ruleset, Mapping) def _dump(element, depth=0): for rule in ruleset.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) outstream.write(self.format_element(element, depth, **kwargs)) outstream.write("\n") if recurse: if maxdepth is None or maxdepth > depth: for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) def iter_unique_child_tags(root, tag): """Iterates through unique child tags for all instances of `tag`. Iteration starts at `root`. """ found_child_tags = set() instances = root.iterdescendants(tag) from itertools import chain child_nodes = chain.from_iterable(i.getchildren() for i in instances) child_tags = (n.tag for n in child_nodes) for t in child_tags: if t not in found_child_tags: found_child_tags.add(t) yield t def iter_tag_list(root): """List all unique tags at and under the `root` node.""" found_tags = set() tags = (n.tag for n in root.iterdescendants() if hasattr(n, 'tag')) for t in tags: if t not in found_tags: found_tags.add(t) yield t def build_tag_graph(root): """Build a python-graph graph of the tag relationships.""" from pygraph.classes.digraph import digraph g = digraph() tags = list(iter_tag_list(root)) g.add_nodes(tags) for parent in tags: for child in iter_unique_child_tags(root, parent): g.add_edge((parent, child)) return g def write_graph(graph, filename, format='png'): """Write a python-graph graph as an image. `format` can be any of those supported by pydot.Dot.write(). """ from pygraph.readwrite.dot import write dotdata = write(graph) from pydot import graph_from_dot_data dotgraph = graph_from_dot_data(dotdata) dotgraph.write(filename, format=format) def write_tag_graph(root, filename, format='png'): graph = build_tag_graph(root) write_graph(graph, filename, format=format) # TODO: refactor this as a class. # TODO: make the dump command's `path` option a general one. def cli(args, in_, out, err, Dumper=Dumper): """Provide a command-line interface to the module functionality. Dumper: xmlearn.Dumper or subclass. Called in response to the `dump` subcommand. Note that this should be the *class*, not an instantiation of it. args: the arguments to be parsed. in_, out, err: open input/output/error files. """ from argparse import ArgumentParser, FileType, Action def instantiate_dumper(ns): kw_from_ns = ['width', 'maxdepth', 'ruleset', 'outstream'] kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if key in kw_from_ns and value is not None) return Dumper(**kwargs) def dump(ns): """Initializes a Dumper with values from the namespace `ns`. False values are filtered out. Dumps `ns.path` from the XML file `ns.infile`. """ dumper = instantiate_dumper(ns) root = etree.parse(ns.infile).getroot() return [dumper.dump(e) for e in ns.path(root)] def list_rulesets(ns): return Dumper.print_rulesets(ruleset=ns.ruleset, verbose=ns.verbose) parser = ArgumentParser() parser.add_argument('-i', '--infile', type=FileType, default=in_, help='The XML file to learn about.\n' 'Defaults to stdin.') parser.add_argument('-p', '--path', default='/*', type=etree.XPath, help='An XPath to be applied to various actions.\n' 'Defaults to the root node.') subparsers = parser.add_subparsers(title='subcommands') def build_dump_parser(subparsers): p_dump = subparsers.add_parser('dump', help='Dump xml data according to a set of rules.', description='Dump xml data according to a set of rules.') p_dump.set_defaults(action=dump, outstream=out) class ListRulesetsAction(Action): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, 'action', list_rulesets) setattr(namespace, 'ruleset', values) p_dump.add_argument('-l', '--list-rulesets', metavar='RULESET', nargs='?', action=ListRulesetsAction, help='Get a list of rulesets ' 'or information about a particular ruleset') p_dump.add_argument('-r', '--ruleset', choices=Dumper.rulesets.keys(), default=Dumper.default_ruleset, help='Which set of rules to apply.\n' 'Defaults to "{0}".' .format(Dumper.default_ruleset)) p_dump.add_argument('-d', '--maxdepth', type=int, help='How many levels to dump.') # TODO: set default width to console width # TODO: also apply the console width to the help display p_dump.add_argument('-w', '--width', type=int, help='The output width of the dump.') p_dump.add_argument('-v', '--verbose', action='store_true', help='Enable verbose ruleset list.\n' 'Only useful with `-l`.') - build_dump_parser(subparsers) def build_tags_parser(subparsers): p_list = subparsers.add_parser('tags', help='Show information about tags.', description='Show information about tags.') def taglist(ns): root = etree.parse(ns.infile).getroot() itemfmt = ' {item}\n' if ns.show_element else '{item}\n' for element in ns.path(root): if ns.show_element: out.write(element.getroottree().getpath(element) + "\n") for item in ns.tagfunc(element, *ns.tagfunc_args): out.write(itemfmt.format(item=item)) p_list.set_defaults(action=taglist, tagfunc=iter_tag_list, tagfunc_args=[]) p_list.add_argument('-e', '--show-element', action='store_true', help='Enables display of the element path.\n' 'Without this option, data from multiple matching elements ' 'will be listed in unbroken series.\n' 'This is mostly useful ' 'when the path selects multiple elements.') class ListChildrenAction(Action): """Change the tag function and set the extra argument.""" def __call__(self, parser, namespace, values, option_string=None): if values: setattr(namespace, 'tagfunc', iter_unique_child_tags) setattr(namespace, 'tagfunc_args', [values]) p_list.add_argument('-c', '--child', nargs='?', metavar='PARENT', action=ListChildrenAction, help='List all tags which appear as children of PARENT.') - build_tags_parser(subparsers) namespace = parser.parse_args(args) return namespace.action(namespace) if __name__ == '__main__': from sys import argv, stdin, stdout, stderr cli(argv[1:], stdin, stdout, stderr)
intuited/xmlearn
5ba71bb32739e16871c528a30bd6750afbd06dd5
Refactor dump subcommand and add tags subcommand Moved dump subcommand parser construction into a subroutine. Wrote a second similar subroutine for the new tags subcommand. Both dump and tags subcommands pass perfunctory testing.
diff --git a/__init__.py b/__init__.py index 8f45657..036cf5a 100755 --- a/__init__.py +++ b/__init__.py @@ -1,281 +1,328 @@ #!/usr/bin/env python """Library and CLI for learning about XML formats.""" from lxml import etree class Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. ruleset: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. outstream: a stream to which the dump will be written. For now, this function is just useful for sussing out the shape of the XML. """ # TODO: write doctest examples # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'full': {None: {'recurse': True}}} default_ruleset = 'full' from sys import stdout outstream = stdout from pprint import PrettyPrinter pformat = PrettyPrinter(indent=2).pformat # Some more defaults. maxdepth = None width = 80 # This should maybe be moved into the CLI. @classmethod def print_rulesets(cls, ruleset=None, outstream=None, format=pformat, verbose=False): """Output ruleset information. If a `ruleset` is given, that ruleset's rules are output. If no `ruleset` is given, a list of rulesets is output. The `verbose` option will cause full ruleset information to be given in the list of rulesets. `format` can be used to specify a different formatting function. """ outstream = outstream if outstream else cls.outstream if ruleset: outstream.write(format(cls.rulesets[ruleset])) else: if verbose: outstream.write(format(cls.rulesets)) else: outstream.writelines("\n".join(cls.rulesets.keys())) outstream.write("\n") def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `ruleset`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `outstream`, `maxdepth`, and `ruleset` object attributes can be overridden without modifying the object. If `ruleset` is not given, `self`'s default ruleset is used. I suspect that actually using XSLT would be a better way to do this. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) # Pull variables from kwargs or self maxdepth, outstream = (kwargs.pop(v, getattr(self, v)) for v in ('maxdepth', 'outstream')) ruleset = kwargs.pop('ruleset', getattr(self, 'ruleset', self.default_ruleset)) if isinstance(ruleset, basestring): ruleset = self.rulesets[ruleset] assert isinstance(ruleset, Mapping) def _dump(element, depth=0): for rule in ruleset.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) outstream.write(self.format_element(element, depth, **kwargs)) outstream.write("\n") if recurse: if maxdepth is None or maxdepth > depth: for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) + def iter_unique_child_tags(root, tag): """Iterates through unique child tags for all instances of `tag`. Iteration starts at `root`. """ found_child_tags = set() instances = root.iterdescendants(tag) from itertools import chain child_nodes = chain.from_iterable(i.getchildren() for i in instances) child_tags = (n.tag for n in child_nodes) for t in child_tags: if t not in found_child_tags: found_child_tags.add(t) yield t def iter_tag_list(root): """List all unique tags at and under the `root` node.""" found_tags = set() tags = (n.tag for n in root.iterdescendants() if hasattr(n, 'tag')) for t in tags: if t not in found_tags: found_tags.add(t) yield t def build_tag_graph(root): """Build a python-graph graph of the tag relationships.""" from pygraph.classes.digraph import digraph g = digraph() tags = list(iter_tag_list(root)) g.add_nodes(tags) for parent in tags: for child in iter_unique_child_tags(root, parent): g.add_edge((parent, child)) return g def write_graph(graph, filename, format='png'): """Write a python-graph graph as an image. `format` can be any of those supported by pydot.Dot.write(). """ from pygraph.readwrite.dot import write dotdata = write(graph) from pydot import graph_from_dot_data dotgraph = graph_from_dot_data(dotdata) dotgraph.write(filename, format=format) def write_tag_graph(root, filename, format='png'): graph = build_tag_graph(root) write_graph(graph, filename, format=format) # TODO: refactor this as a class. # TODO: make the dump command's `path` option a general one. def cli(args, in_, out, err, Dumper=Dumper): """Provide a command-line interface to the module functionality. Dumper: xmlearn.Dumper or subclass. Called in response to the `dump` subcommand. Note that this should be the *class*, not an instantiation of it. args: the arguments to be parsed. in_, out, err: open input/output/error files. """ from argparse import ArgumentParser, FileType, Action def instantiate_dumper(ns): kw_from_ns = ['width', 'maxdepth', 'ruleset', 'outstream'] kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if key in kw_from_ns and value is not None) return Dumper(**kwargs) def dump(ns): """Initializes a Dumper with values from the namespace `ns`. False values are filtered out. Dumps `ns.path` from the XML file `ns.infile`. """ dumper = instantiate_dumper(ns) root = etree.parse(ns.infile).getroot() return [dumper.dump(e) for e in ns.path(root)] def list_rulesets(ns): return Dumper.print_rulesets(ruleset=ns.ruleset, verbose=ns.verbose) parser = ArgumentParser() parser.add_argument('-i', '--infile', type=FileType, default=in_, help='The XML file to learn about.\n' 'Defaults to stdin.') parser.add_argument('-p', '--path', default='/*', type=etree.XPath, help='An XPath to be applied to various actions.\n' 'Defaults to the root node.') - class ListRulesetsAction(Action): - def __call__(self, parser, namespace, values, option_string=None): - setattr(namespace, 'action', list_rulesets) - setattr(namespace, 'ruleset', values) - subparsers = parser.add_subparsers(title='subcommands') - p_dump = subparsers.add_parser('dump', - help='Dump xml data according to a set of rules.', - description='Dump xml data according to a set of rules.') - p_dump.set_defaults(action=dump, outstream=out) - p_dump.add_argument('-l', '--list-rulesets', metavar='RULESET', - nargs='?', action=ListRulesetsAction, - help='Get a list of rulesets ' - 'or information about a particular ruleset') - p_dump.add_argument('-r', '--ruleset', - choices=Dumper.rulesets.keys(), - default=Dumper.default_ruleset, - help='Which set of rules to apply.\nDefaults to "{0}".' - .format(Dumper.default_ruleset)) - p_dump.add_argument('-d', '--maxdepth', type=int, - help='How many levels to dump.') - # TODO: set default width to console width - p_dump.add_argument('-w', '--width', type=int, - help='The output width of the dump.') - p_dump.add_argument('-v', '--verbose', action='store_true', - help='Enable verbose ruleset list.\n' - 'Only useful with `-l`.') + + def build_dump_parser(subparsers): + p_dump = subparsers.add_parser('dump', + help='Dump xml data according to a set of rules.', + description='Dump xml data according to a set of rules.') + + p_dump.set_defaults(action=dump, outstream=out) + + class ListRulesetsAction(Action): + def __call__(self, parser, namespace, values, option_string=None): + setattr(namespace, 'action', list_rulesets) + setattr(namespace, 'ruleset', values) + p_dump.add_argument('-l', '--list-rulesets', metavar='RULESET', + nargs='?', action=ListRulesetsAction, + help='Get a list of rulesets ' + 'or information about a particular ruleset') + + p_dump.add_argument('-r', '--ruleset', + choices=Dumper.rulesets.keys(), + default=Dumper.default_ruleset, + help='Which set of rules to apply.\n' + 'Defaults to "{0}".' + .format(Dumper.default_ruleset)) + + p_dump.add_argument('-d', '--maxdepth', type=int, + help='How many levels to dump.') + # TODO: set default width to console width + # TODO: also apply the console width to the help display + p_dump.add_argument('-w', '--width', type=int, + help='The output width of the dump.') + p_dump.add_argument('-v', '--verbose', action='store_true', + help='Enable verbose ruleset list.\n' + 'Only useful with `-l`.') + + build_dump_parser(subparsers) + + + def build_tags_parser(subparsers): + p_list = subparsers.add_parser('tags', + help='Show information about tags.', + description='Show information about tags.') + + def taglist(ns): + root = etree.parse(ns.infile).getroot() + itemfmt = ' {item}\n' if ns.show_element else '{item}\n' + for element in ns.path(root): + if ns.show_element: + out.write(element.getroottree().getpath(element) + "\n") + for item in ns.tagfunc(element, *ns.tagfunc_args): + out.write(itemfmt.format(item=item)) + + p_list.set_defaults(action=taglist, + tagfunc=iter_tag_list, tagfunc_args=[]) + + p_list.add_argument('-e', '--show-element', action='store_true', + help='Enables display of the element path.\n' + 'Without this option, data from multiple matching elements ' + 'will be listed in unbroken series.\n' + 'This is mostly useful ' + 'when the path selects multiple elements.') + + class ListChildrenAction(Action): + """Change the tag function and set the extra argument.""" + def __call__(self, parser, namespace, values, option_string=None): + if values: + setattr(namespace, 'tagfunc', iter_unique_child_tags) + setattr(namespace, 'tagfunc_args', [values]) + p_list.add_argument('-c', '--child', nargs='?', metavar='PARENT', + action=ListChildrenAction, + help='List all tags which appear as children of PARENT.') + + build_tags_parser(subparsers) namespace = parser.parse_args(args) return namespace.action(namespace) if __name__ == '__main__': from sys import argv, stdin, stdout, stderr cli(argv[1:], stdin, stdout, stderr)
intuited/xmlearn
1bdc70ab4572eed1dee024f40089f1a6bb21276d
move the `dump` subcommand's path argument up to the top level and make it an option.
diff --git a/__init__.py b/__init__.py index 90177be..8f45657 100755 --- a/__init__.py +++ b/__init__.py @@ -1,282 +1,281 @@ #!/usr/bin/env python """Library and CLI for learning about XML formats.""" from lxml import etree class Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. ruleset: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. outstream: a stream to which the dump will be written. For now, this function is just useful for sussing out the shape of the XML. """ # TODO: write doctest examples # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'full': {None: {'recurse': True}}} default_ruleset = 'full' from sys import stdout outstream = stdout from pprint import PrettyPrinter pformat = PrettyPrinter(indent=2).pformat # Some more defaults. maxdepth = None width = 80 # This should maybe be moved into the CLI. @classmethod def print_rulesets(cls, ruleset=None, outstream=None, format=pformat, verbose=False): """Output ruleset information. If a `ruleset` is given, that ruleset's rules are output. If no `ruleset` is given, a list of rulesets is output. The `verbose` option will cause full ruleset information to be given in the list of rulesets. `format` can be used to specify a different formatting function. """ outstream = outstream if outstream else cls.outstream if ruleset: outstream.write(format(cls.rulesets[ruleset])) else: if verbose: outstream.write(format(cls.rulesets)) else: outstream.writelines("\n".join(cls.rulesets.keys())) outstream.write("\n") def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `ruleset`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `outstream`, `maxdepth`, and `ruleset` object attributes can be overridden without modifying the object. If `ruleset` is not given, `self`'s default ruleset is used. I suspect that actually using XSLT would be a better way to do this. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) # Pull variables from kwargs or self maxdepth, outstream = (kwargs.pop(v, getattr(self, v)) for v in ('maxdepth', 'outstream')) ruleset = kwargs.pop('ruleset', getattr(self, 'ruleset', self.default_ruleset)) if isinstance(ruleset, basestring): ruleset = self.rulesets[ruleset] assert isinstance(ruleset, Mapping) def _dump(element, depth=0): for rule in ruleset.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) outstream.write(self.format_element(element, depth, **kwargs)) outstream.write("\n") if recurse: if maxdepth is None or maxdepth > depth: for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) def iter_unique_child_tags(root, tag): """Iterates through unique child tags for all instances of `tag`. Iteration starts at `root`. """ found_child_tags = set() instances = root.iterdescendants(tag) from itertools import chain child_nodes = chain.from_iterable(i.getchildren() for i in instances) child_tags = (n.tag for n in child_nodes) for t in child_tags: if t not in found_child_tags: found_child_tags.add(t) yield t def iter_tag_list(root): """List all unique tags at and under the `root` node.""" found_tags = set() tags = (n.tag for n in root.iterdescendants() if hasattr(n, 'tag')) for t in tags: if t not in found_tags: found_tags.add(t) yield t def build_tag_graph(root): """Build a python-graph graph of the tag relationships.""" from pygraph.classes.digraph import digraph g = digraph() tags = list(iter_tag_list(root)) g.add_nodes(tags) for parent in tags: for child in iter_unique_child_tags(root, parent): g.add_edge((parent, child)) return g def write_graph(graph, filename, format='png'): """Write a python-graph graph as an image. `format` can be any of those supported by pydot.Dot.write(). """ from pygraph.readwrite.dot import write dotdata = write(graph) from pydot import graph_from_dot_data dotgraph = graph_from_dot_data(dotdata) dotgraph.write(filename, format=format) def write_tag_graph(root, filename, format='png'): graph = build_tag_graph(root) write_graph(graph, filename, format=format) # TODO: refactor this as a class. # TODO: make the dump command's `path` option a general one. def cli(args, in_, out, err, Dumper=Dumper): """Provide a command-line interface to the module functionality. Dumper: xmlearn.Dumper or subclass. Called in response to the `dump` subcommand. Note that this should be the *class*, not an instantiation of it. args: the arguments to be parsed. in_, out, err: open input/output/error files. """ from argparse import ArgumentParser, FileType, Action def instantiate_dumper(ns): kw_from_ns = ['width', 'maxdepth', 'ruleset', 'outstream'] kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if key in kw_from_ns and value is not None) return Dumper(**kwargs) def dump(ns): """Initializes a Dumper with values from the namespace `ns`. False values are filtered out. Dumps `ns.path` from the XML file `ns.infile`. """ dumper = instantiate_dumper(ns) root = etree.parse(ns.infile).getroot() return [dumper.dump(e) for e in ns.path(root)] def list_rulesets(ns): return Dumper.print_rulesets(ruleset=ns.ruleset, verbose=ns.verbose) parser = ArgumentParser() parser.add_argument('-i', '--infile', type=FileType, default=in_, help='The XML file to learn about.\n' 'Defaults to stdin.') + parser.add_argument('-p', '--path', default='/*', type=etree.XPath, + help='An XPath to be applied to various actions.\n' + 'Defaults to the root node.') class ListRulesetsAction(Action): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, 'action', list_rulesets) setattr(namespace, 'ruleset', values) subparsers = parser.add_subparsers(title='subcommands') p_dump = subparsers.add_parser('dump', help='Dump xml data according to a set of rules.', description='Dump xml data according to a set of rules.') p_dump.set_defaults(action=dump, outstream=out) p_dump.add_argument('-l', '--list-rulesets', metavar='RULESET', nargs='?', action=ListRulesetsAction, help='Get a list of rulesets ' 'or information about a particular ruleset') p_dump.add_argument('-r', '--ruleset', choices=Dumper.rulesets.keys(), default=Dumper.default_ruleset, help='Which set of rules to apply.\nDefaults to "{0}".' .format(Dumper.default_ruleset)) p_dump.add_argument('-d', '--maxdepth', type=int, help='How many levels to dump.') # TODO: set default width to console width p_dump.add_argument('-w', '--width', type=int, help='The output width of the dump.') p_dump.add_argument('-v', '--verbose', action='store_true', help='Enable verbose ruleset list.\n' 'Only useful with `-l`.') - p_dump.add_argument(dest='path', nargs='?', default='/*', type=etree.XPath, - help='The XPath to the nodes to be dumped.\n' - 'Defaults to the root node.') - namespace = parser.parse_args(args) return namespace.action(namespace) if __name__ == '__main__': from sys import argv, stdin, stdout, stderr cli(argv[1:], stdin, stdout, stderr)
intuited/xmlearn
d23e6c71a0175566b9f8f0418c082bdb75ca361a
refactor non-Dumper methods as top-level module functions. Totally untested but mostly braindead.
diff --git a/__init__.py b/__init__.py index 87c1179..90177be 100755 --- a/__init__.py +++ b/__init__.py @@ -1,282 +1,282 @@ #!/usr/bin/env python """Library and CLI for learning about XML formats.""" from lxml import etree class Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. ruleset: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. outstream: a stream to which the dump will be written. For now, this function is just useful for sussing out the shape of the XML. """ # TODO: write doctest examples # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'full': {None: {'recurse': True}}} default_ruleset = 'full' from sys import stdout outstream = stdout from pprint import PrettyPrinter pformat = PrettyPrinter(indent=2).pformat # Some more defaults. maxdepth = None width = 80 # This should maybe be moved into the CLI. @classmethod def print_rulesets(cls, ruleset=None, outstream=None, format=pformat, verbose=False): """Output ruleset information. If a `ruleset` is given, that ruleset's rules are output. If no `ruleset` is given, a list of rulesets is output. The `verbose` option will cause full ruleset information to be given in the list of rulesets. `format` can be used to specify a different formatting function. """ outstream = outstream if outstream else cls.outstream if ruleset: outstream.write(format(cls.rulesets[ruleset])) else: if verbose: outstream.write(format(cls.rulesets)) else: outstream.writelines("\n".join(cls.rulesets.keys())) outstream.write("\n") def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `ruleset`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `outstream`, `maxdepth`, and `ruleset` object attributes can be overridden without modifying the object. If `ruleset` is not given, `self`'s default ruleset is used. I suspect that actually using XSLT would be a better way to do this. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) # Pull variables from kwargs or self maxdepth, outstream = (kwargs.pop(v, getattr(self, v)) for v in ('maxdepth', 'outstream')) ruleset = kwargs.pop('ruleset', getattr(self, 'ruleset', self.default_ruleset)) if isinstance(ruleset, basestring): ruleset = self.rulesets[ruleset] assert isinstance(ruleset, Mapping) def _dump(element, depth=0): for rule in ruleset.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) outstream.write(self.format_element(element, depth, **kwargs)) outstream.write("\n") if recurse: if maxdepth is None or maxdepth > depth: for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) - def iter_unique_child_tags(self, root, tag): - """Iterates through unique child tags for all instances of `tag`. +def iter_unique_child_tags(root, tag): + """Iterates through unique child tags for all instances of `tag`. - Iteration starts at `root`. - """ - found_child_tags = set() - instances = root.iterdescendants(tag) - from itertools import chain - child_nodes = chain.from_iterable(i.getchildren() for i in instances) - child_tags = (n.tag for n in child_nodes) - for t in child_tags: - if t not in found_child_tags: - found_child_tags.add(t) - yield t - - def iter_tag_list(self, root): - """List all unique tags at and under the `root` node.""" - found_tags = set() - tags = (n.tag for n in root.iterdescendants() if hasattr(n, 'tag')) - for t in tags: - if t not in found_tags: - found_tags.add(t) - yield t - - def build_tag_graph(self, root): - """Build a python-graph graph of the tag relationships.""" - from pygraph.classes.digraph import digraph - - g = digraph() - - tags = list(self.iter_tag_list(root)) - g.add_nodes(tags) - - for parent in tags: - for child in self.iter_unique_child_tags(root, parent): - g.add_edge((parent, child)) - - return g - - def write_graph(self, graph, filename, format='png'): - """Write a python-graph graph as an image. - - `format` can be any of those supported by pydot.Dot.write(). - """ - from pygraph.readwrite.dot import write - dotdata = write(graph) + Iteration starts at `root`. + """ + found_child_tags = set() + instances = root.iterdescendants(tag) + from itertools import chain + child_nodes = chain.from_iterable(i.getchildren() for i in instances) + child_tags = (n.tag for n in child_nodes) + for t in child_tags: + if t not in found_child_tags: + found_child_tags.add(t) + yield t + +def iter_tag_list(root): + """List all unique tags at and under the `root` node.""" + found_tags = set() + tags = (n.tag for n in root.iterdescendants() if hasattr(n, 'tag')) + for t in tags: + if t not in found_tags: + found_tags.add(t) + yield t + +def build_tag_graph(root): + """Build a python-graph graph of the tag relationships.""" + from pygraph.classes.digraph import digraph + + g = digraph() + + tags = list(iter_tag_list(root)) + g.add_nodes(tags) + + for parent in tags: + for child in iter_unique_child_tags(root, parent): + g.add_edge((parent, child)) + + return g + +def write_graph(graph, filename, format='png'): + """Write a python-graph graph as an image. + + `format` can be any of those supported by pydot.Dot.write(). + """ + from pygraph.readwrite.dot import write + dotdata = write(graph) - from pydot import graph_from_dot_data - dotgraph = graph_from_dot_data(dotdata) - dotgraph.write(filename, format=format) + from pydot import graph_from_dot_data + dotgraph = graph_from_dot_data(dotdata) + dotgraph.write(filename, format=format) - def write_tag_graph(self, root, filename, format='png'): - graph = self.build_tag_graph(root) - self.write_graph(graph, filename, format=format) +def write_tag_graph(root, filename, format='png'): + graph = build_tag_graph(root) + write_graph(graph, filename, format=format) # TODO: refactor this as a class. # TODO: make the dump command's `path` option a general one. def cli(args, in_, out, err, Dumper=Dumper): """Provide a command-line interface to the module functionality. Dumper: xmlearn.Dumper or subclass. Called in response to the `dump` subcommand. Note that this should be the *class*, not an instantiation of it. args: the arguments to be parsed. in_, out, err: open input/output/error files. """ from argparse import ArgumentParser, FileType, Action def instantiate_dumper(ns): kw_from_ns = ['width', 'maxdepth', 'ruleset', 'outstream'] kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if key in kw_from_ns and value is not None) return Dumper(**kwargs) def dump(ns): """Initializes a Dumper with values from the namespace `ns`. False values are filtered out. Dumps `ns.path` from the XML file `ns.infile`. """ dumper = instantiate_dumper(ns) root = etree.parse(ns.infile).getroot() return [dumper.dump(e) for e in ns.path(root)] def list_rulesets(ns): return Dumper.print_rulesets(ruleset=ns.ruleset, verbose=ns.verbose) parser = ArgumentParser() parser.add_argument('-i', '--infile', type=FileType, default=in_, help='The XML file to learn about.\n' 'Defaults to stdin.') class ListRulesetsAction(Action): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, 'action', list_rulesets) setattr(namespace, 'ruleset', values) subparsers = parser.add_subparsers(title='subcommands') p_dump = subparsers.add_parser('dump', help='Dump xml data according to a set of rules.', description='Dump xml data according to a set of rules.') p_dump.set_defaults(action=dump, outstream=out) p_dump.add_argument('-l', '--list-rulesets', metavar='RULESET', nargs='?', action=ListRulesetsAction, help='Get a list of rulesets ' 'or information about a particular ruleset') p_dump.add_argument('-r', '--ruleset', choices=Dumper.rulesets.keys(), default=Dumper.default_ruleset, help='Which set of rules to apply.\nDefaults to "{0}".' .format(Dumper.default_ruleset)) p_dump.add_argument('-d', '--maxdepth', type=int, help='How many levels to dump.') # TODO: set default width to console width p_dump.add_argument('-w', '--width', type=int, help='The output width of the dump.') p_dump.add_argument('-v', '--verbose', action='store_true', help='Enable verbose ruleset list.\n' 'Only useful with `-l`.') p_dump.add_argument(dest='path', nargs='?', default='/*', type=etree.XPath, help='The XPath to the nodes to be dumped.\n' 'Defaults to the root node.') namespace = parser.parse_args(args) return namespace.action(namespace) if __name__ == '__main__': from sys import argv, stdin, stdout, stderr cli(argv[1:], stdin, stdout, stderr)
intuited/xmlearn
ec601e35ffc937a10d0f65414c059edb38976255
refactor dumper instantiation and add check of key against `kw_from_ns`
diff --git a/__init__.py b/__init__.py index 7a06283..87c1179 100755 --- a/__init__.py +++ b/__init__.py @@ -1,279 +1,282 @@ #!/usr/bin/env python """Library and CLI for learning about XML formats.""" from lxml import etree class Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. ruleset: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. outstream: a stream to which the dump will be written. For now, this function is just useful for sussing out the shape of the XML. """ # TODO: write doctest examples # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'full': {None: {'recurse': True}}} default_ruleset = 'full' from sys import stdout outstream = stdout from pprint import PrettyPrinter pformat = PrettyPrinter(indent=2).pformat # Some more defaults. maxdepth = None width = 80 # This should maybe be moved into the CLI. @classmethod def print_rulesets(cls, ruleset=None, outstream=None, format=pformat, verbose=False): """Output ruleset information. If a `ruleset` is given, that ruleset's rules are output. If no `ruleset` is given, a list of rulesets is output. The `verbose` option will cause full ruleset information to be given in the list of rulesets. `format` can be used to specify a different formatting function. """ outstream = outstream if outstream else cls.outstream if ruleset: outstream.write(format(cls.rulesets[ruleset])) else: if verbose: outstream.write(format(cls.rulesets)) else: outstream.writelines("\n".join(cls.rulesets.keys())) outstream.write("\n") def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `ruleset`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `outstream`, `maxdepth`, and `ruleset` object attributes can be overridden without modifying the object. If `ruleset` is not given, `self`'s default ruleset is used. I suspect that actually using XSLT would be a better way to do this. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) # Pull variables from kwargs or self maxdepth, outstream = (kwargs.pop(v, getattr(self, v)) for v in ('maxdepth', 'outstream')) ruleset = kwargs.pop('ruleset', getattr(self, 'ruleset', self.default_ruleset)) if isinstance(ruleset, basestring): ruleset = self.rulesets[ruleset] assert isinstance(ruleset, Mapping) def _dump(element, depth=0): for rule in ruleset.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) outstream.write(self.format_element(element, depth, **kwargs)) outstream.write("\n") if recurse: if maxdepth is None or maxdepth > depth: for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) def iter_unique_child_tags(self, root, tag): """Iterates through unique child tags for all instances of `tag`. Iteration starts at `root`. """ found_child_tags = set() instances = root.iterdescendants(tag) from itertools import chain child_nodes = chain.from_iterable(i.getchildren() for i in instances) child_tags = (n.tag for n in child_nodes) for t in child_tags: if t not in found_child_tags: found_child_tags.add(t) yield t def iter_tag_list(self, root): """List all unique tags at and under the `root` node.""" found_tags = set() tags = (n.tag for n in root.iterdescendants() if hasattr(n, 'tag')) for t in tags: if t not in found_tags: found_tags.add(t) yield t def build_tag_graph(self, root): """Build a python-graph graph of the tag relationships.""" from pygraph.classes.digraph import digraph g = digraph() tags = list(self.iter_tag_list(root)) g.add_nodes(tags) for parent in tags: for child in self.iter_unique_child_tags(root, parent): g.add_edge((parent, child)) return g def write_graph(self, graph, filename, format='png'): """Write a python-graph graph as an image. `format` can be any of those supported by pydot.Dot.write(). """ from pygraph.readwrite.dot import write dotdata = write(graph) from pydot import graph_from_dot_data dotgraph = graph_from_dot_data(dotdata) dotgraph.write(filename, format=format) def write_tag_graph(self, root, filename, format='png'): graph = self.build_tag_graph(root) self.write_graph(graph, filename, format=format) # TODO: refactor this as a class. # TODO: make the dump command's `path` option a general one. def cli(args, in_, out, err, Dumper=Dumper): """Provide a command-line interface to the module functionality. Dumper: xmlearn.Dumper or subclass. Called in response to the `dump` subcommand. Note that this should be the *class*, not an instantiation of it. args: the arguments to be parsed. in_, out, err: open input/output/error files. """ from argparse import ArgumentParser, FileType, Action + def instantiate_dumper(ns): + kw_from_ns = ['width', 'maxdepth', 'ruleset', 'outstream'] + kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() + if key in kw_from_ns and value is not None) + return Dumper(**kwargs) + def dump(ns): """Initializes a Dumper with values from the namespace `ns`. False values are filtered out. Dumps `ns.path` from the XML file `ns.infile`. """ - kw_from_ns = ['width', 'maxdepth', 'ruleset', 'outstream'] - kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() - if value is not None) - dumper = Dumper(**kwargs) + dumper = instantiate_dumper(ns) root = etree.parse(ns.infile).getroot() return [dumper.dump(e) for e in ns.path(root)] def list_rulesets(ns): return Dumper.print_rulesets(ruleset=ns.ruleset, verbose=ns.verbose) parser = ArgumentParser() parser.add_argument('-i', '--infile', type=FileType, default=in_, help='The XML file to learn about.\n' 'Defaults to stdin.') class ListRulesetsAction(Action): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, 'action', list_rulesets) setattr(namespace, 'ruleset', values) subparsers = parser.add_subparsers(title='subcommands') p_dump = subparsers.add_parser('dump', help='Dump xml data according to a set of rules.', description='Dump xml data according to a set of rules.') p_dump.set_defaults(action=dump, outstream=out) p_dump.add_argument('-l', '--list-rulesets', metavar='RULESET', nargs='?', action=ListRulesetsAction, help='Get a list of rulesets ' 'or information about a particular ruleset') p_dump.add_argument('-r', '--ruleset', choices=Dumper.rulesets.keys(), default=Dumper.default_ruleset, help='Which set of rules to apply.\nDefaults to "{0}".' .format(Dumper.default_ruleset)) p_dump.add_argument('-d', '--maxdepth', type=int, help='How many levels to dump.') # TODO: set default width to console width p_dump.add_argument('-w', '--width', type=int, help='The output width of the dump.') p_dump.add_argument('-v', '--verbose', action='store_true', help='Enable verbose ruleset list.\n' 'Only useful with `-l`.') p_dump.add_argument(dest='path', nargs='?', default='/*', type=etree.XPath, help='The XPath to the nodes to be dumped.\n' 'Defaults to the root node.') namespace = parser.parse_args(args) return namespace.action(namespace) if __name__ == '__main__': from sys import argv, stdin, stdout, stderr cli(argv[1:], stdin, stdout, stderr)
intuited/xmlearn
52af6b1128c9c8b975835fce1385adfeb5fa4ef3
remove vestigial function
diff --git a/__init__.py b/__init__.py index 3bb5c6e..7a06283 100755 --- a/__init__.py +++ b/__init__.py @@ -1,289 +1,279 @@ #!/usr/bin/env python """Library and CLI for learning about XML formats.""" from lxml import etree class Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. ruleset: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. outstream: a stream to which the dump will be written. For now, this function is just useful for sussing out the shape of the XML. """ # TODO: write doctest examples # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'full': {None: {'recurse': True}}} default_ruleset = 'full' from sys import stdout outstream = stdout from pprint import PrettyPrinter pformat = PrettyPrinter(indent=2).pformat # Some more defaults. maxdepth = None width = 80 # This should maybe be moved into the CLI. @classmethod def print_rulesets(cls, ruleset=None, outstream=None, format=pformat, verbose=False): """Output ruleset information. If a `ruleset` is given, that ruleset's rules are output. If no `ruleset` is given, a list of rulesets is output. The `verbose` option will cause full ruleset information to be given in the list of rulesets. `format` can be used to specify a different formatting function. """ outstream = outstream if outstream else cls.outstream if ruleset: outstream.write(format(cls.rulesets[ruleset])) else: if verbose: outstream.write(format(cls.rulesets)) else: outstream.writelines("\n".join(cls.rulesets.keys())) outstream.write("\n") def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `ruleset`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `outstream`, `maxdepth`, and `ruleset` object attributes can be overridden without modifying the object. If `ruleset` is not given, `self`'s default ruleset is used. I suspect that actually using XSLT would be a better way to do this. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) # Pull variables from kwargs or self maxdepth, outstream = (kwargs.pop(v, getattr(self, v)) for v in ('maxdepth', 'outstream')) ruleset = kwargs.pop('ruleset', getattr(self, 'ruleset', self.default_ruleset)) if isinstance(ruleset, basestring): ruleset = self.rulesets[ruleset] assert isinstance(ruleset, Mapping) def _dump(element, depth=0): for rule in ruleset.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) outstream.write(self.format_element(element, depth, **kwargs)) outstream.write("\n") if recurse: if maxdepth is None or maxdepth > depth: for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) def iter_unique_child_tags(self, root, tag): """Iterates through unique child tags for all instances of `tag`. Iteration starts at `root`. """ found_child_tags = set() instances = root.iterdescendants(tag) from itertools import chain child_nodes = chain.from_iterable(i.getchildren() for i in instances) child_tags = (n.tag for n in child_nodes) for t in child_tags: if t not in found_child_tags: found_child_tags.add(t) yield t def iter_tag_list(self, root): """List all unique tags at and under the `root` node.""" found_tags = set() tags = (n.tag for n in root.iterdescendants() if hasattr(n, 'tag')) for t in tags: if t not in found_tags: found_tags.add(t) yield t def build_tag_graph(self, root): """Build a python-graph graph of the tag relationships.""" from pygraph.classes.digraph import digraph g = digraph() tags = list(self.iter_tag_list(root)) g.add_nodes(tags) for parent in tags: for child in self.iter_unique_child_tags(root, parent): g.add_edge((parent, child)) return g def write_graph(self, graph, filename, format='png'): """Write a python-graph graph as an image. `format` can be any of those supported by pydot.Dot.write(). """ from pygraph.readwrite.dot import write dotdata = write(graph) from pydot import graph_from_dot_data dotgraph = graph_from_dot_data(dotdata) dotgraph.write(filename, format=format) def write_tag_graph(self, root, filename, format='png'): graph = self.build_tag_graph(root) self.write_graph(graph, filename, format=format) # TODO: refactor this as a class. # TODO: make the dump command's `path` option a general one. def cli(args, in_, out, err, Dumper=Dumper): """Provide a command-line interface to the module functionality. Dumper: xmlearn.Dumper or subclass. Called in response to the `dump` subcommand. Note that this should be the *class*, not an instantiation of it. args: the arguments to be parsed. in_, out, err: open input/output/error files. """ from argparse import ArgumentParser, FileType, Action - def call_function(ns): - """Calls `ns.function`, passing arguments as determined by `ns`. - - Attributes of `ns` which are listed in `ns.kw_from_ns` - are added to the set of keyword arguments passed to `ns.function`. - """ - kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() - if key in ns.kw_from_ns) - return ns.function(**kwargs) - def dump(ns): """Initializes a Dumper with values from the namespace `ns`. False values are filtered out. Dumps `ns.path` from the XML file `ns.infile`. """ kw_from_ns = ['width', 'maxdepth', 'ruleset', 'outstream'] kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if value is not None) dumper = Dumper(**kwargs) root = etree.parse(ns.infile).getroot() return [dumper.dump(e) for e in ns.path(root)] def list_rulesets(ns): return Dumper.print_rulesets(ruleset=ns.ruleset, verbose=ns.verbose) parser = ArgumentParser() parser.add_argument('-i', '--infile', type=FileType, default=in_, help='The XML file to learn about.\n' 'Defaults to stdin.') class ListRulesetsAction(Action): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, 'action', list_rulesets) setattr(namespace, 'ruleset', values) subparsers = parser.add_subparsers(title='subcommands') p_dump = subparsers.add_parser('dump', help='Dump xml data according to a set of rules.', description='Dump xml data according to a set of rules.') p_dump.set_defaults(action=dump, outstream=out) p_dump.add_argument('-l', '--list-rulesets', metavar='RULESET', nargs='?', action=ListRulesetsAction, help='Get a list of rulesets ' 'or information about a particular ruleset') p_dump.add_argument('-r', '--ruleset', choices=Dumper.rulesets.keys(), default=Dumper.default_ruleset, help='Which set of rules to apply.\nDefaults to "{0}".' .format(Dumper.default_ruleset)) p_dump.add_argument('-d', '--maxdepth', type=int, help='How many levels to dump.') # TODO: set default width to console width p_dump.add_argument('-w', '--width', type=int, help='The output width of the dump.') p_dump.add_argument('-v', '--verbose', action='store_true', help='Enable verbose ruleset list.\n' 'Only useful with `-l`.') p_dump.add_argument(dest='path', nargs='?', default='/*', type=etree.XPath, help='The XPath to the nodes to be dumped.\n' 'Defaults to the root node.') namespace = parser.parse_args(args) return namespace.action(namespace) if __name__ == '__main__': from sys import argv, stdin, stdout, stderr cli(argv[1:], stdin, stdout, stderr)
intuited/xmlearn
f661478366f5ebd5d2f019a972129047a4db2086
revise documentation
diff --git a/__init__.py b/__init__.py index b2d49cb..3bb5c6e 100755 --- a/__init__.py +++ b/__init__.py @@ -1,290 +1,289 @@ #!/usr/bin/env python """Library and CLI for learning about XML formats.""" from lxml import etree class Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. ruleset: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. outstream: a stream to which the dump will be written. For now, this function is just useful for sussing out the shape of the XML. """ # TODO: write doctest examples # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'full': {None: {'recurse': True}}} default_ruleset = 'full' from sys import stdout outstream = stdout from pprint import PrettyPrinter pformat = PrettyPrinter(indent=2).pformat # Some more defaults. maxdepth = None width = 80 # This should maybe be moved into the CLI. @classmethod def print_rulesets(cls, ruleset=None, outstream=None, format=pformat, verbose=False): """Output ruleset information. If a `ruleset` is given, that ruleset's rules are output. If no `ruleset` is given, a list of rulesets is output. The `verbose` option will cause full ruleset information to be given in the list of rulesets. `format` can be used to specify a different formatting function. """ outstream = outstream if outstream else cls.outstream if ruleset: outstream.write(format(cls.rulesets[ruleset])) else: if verbose: outstream.write(format(cls.rulesets)) else: outstream.writelines("\n".join(cls.rulesets.keys())) outstream.write("\n") def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `ruleset`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `outstream`, `maxdepth`, and `ruleset` object attributes can be overridden without modifying the object. If `ruleset` is not given, `self`'s default ruleset is used. I suspect that actually using XSLT would be a better way to do this. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) # Pull variables from kwargs or self maxdepth, outstream = (kwargs.pop(v, getattr(self, v)) for v in ('maxdepth', 'outstream')) ruleset = kwargs.pop('ruleset', getattr(self, 'ruleset', self.default_ruleset)) if isinstance(ruleset, basestring): ruleset = self.rulesets[ruleset] assert isinstance(ruleset, Mapping) def _dump(element, depth=0): for rule in ruleset.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) outstream.write(self.format_element(element, depth, **kwargs)) outstream.write("\n") if recurse: if maxdepth is None or maxdepth > depth: for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) def iter_unique_child_tags(self, root, tag): """Iterates through unique child tags for all instances of `tag`. Iteration starts at `root`. """ found_child_tags = set() instances = root.iterdescendants(tag) from itertools import chain child_nodes = chain.from_iterable(i.getchildren() for i in instances) child_tags = (n.tag for n in child_nodes) for t in child_tags: if t not in found_child_tags: found_child_tags.add(t) yield t def iter_tag_list(self, root): """List all unique tags at and under the `root` node.""" found_tags = set() tags = (n.tag for n in root.iterdescendants() if hasattr(n, 'tag')) for t in tags: if t not in found_tags: found_tags.add(t) yield t def build_tag_graph(self, root): """Build a python-graph graph of the tag relationships.""" from pygraph.classes.digraph import digraph g = digraph() tags = list(self.iter_tag_list(root)) g.add_nodes(tags) for parent in tags: for child in self.iter_unique_child_tags(root, parent): g.add_edge((parent, child)) return g def write_graph(self, graph, filename, format='png'): """Write a python-graph graph as an image. `format` can be any of those supported by pydot.Dot.write(). """ from pygraph.readwrite.dot import write dotdata = write(graph) from pydot import graph_from_dot_data dotgraph = graph_from_dot_data(dotdata) dotgraph.write(filename, format=format) def write_tag_graph(self, root, filename, format='png'): graph = self.build_tag_graph(root) self.write_graph(graph, filename, format=format) # TODO: refactor this as a class. # TODO: make the dump command's `path` option a general one. def cli(args, in_, out, err, Dumper=Dumper): """Provide a command-line interface to the module functionality. Dumper: xmlearn.Dumper or subclass. Called in response to the `dump` subcommand. Note that this should be the *class*, not an instantiation of it. args: the arguments to be parsed. in_, out, err: open input/output/error files. """ from argparse import ArgumentParser, FileType, Action def call_function(ns): """Calls `ns.function`, passing arguments as determined by `ns`. Attributes of `ns` which are listed in `ns.kw_from_ns` are added to the set of keyword arguments passed to `ns.function`. """ kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if key in ns.kw_from_ns) return ns.function(**kwargs) def dump(ns): """Initializes a Dumper with values from the namespace `ns`. False values are filtered out. - - Calls its `dump` method, sending output to `out`. + Dumps `ns.path` from the XML file `ns.infile`. """ kw_from_ns = ['width', 'maxdepth', 'ruleset', 'outstream'] kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if value is not None) dumper = Dumper(**kwargs) root = etree.parse(ns.infile).getroot() return [dumper.dump(e) for e in ns.path(root)] def list_rulesets(ns): return Dumper.print_rulesets(ruleset=ns.ruleset, verbose=ns.verbose) parser = ArgumentParser() parser.add_argument('-i', '--infile', type=FileType, default=in_, help='The XML file to learn about.\n' 'Defaults to stdin.') class ListRulesetsAction(Action): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, 'action', list_rulesets) setattr(namespace, 'ruleset', values) subparsers = parser.add_subparsers(title='subcommands') p_dump = subparsers.add_parser('dump', help='Dump xml data according to a set of rules.', description='Dump xml data according to a set of rules.') p_dump.set_defaults(action=dump, outstream=out) p_dump.add_argument('-l', '--list-rulesets', metavar='RULESET', nargs='?', action=ListRulesetsAction, help='Get a list of rulesets ' 'or information about a particular ruleset') p_dump.add_argument('-r', '--ruleset', choices=Dumper.rulesets.keys(), default=Dumper.default_ruleset, help='Which set of rules to apply.\nDefaults to "{0}".' .format(Dumper.default_ruleset)) p_dump.add_argument('-d', '--maxdepth', type=int, help='How many levels to dump.') # TODO: set default width to console width p_dump.add_argument('-w', '--width', type=int, help='The output width of the dump.') p_dump.add_argument('-v', '--verbose', action='store_true', help='Enable verbose ruleset list.\n' 'Only useful with `-l`.') p_dump.add_argument(dest='path', nargs='?', default='/*', type=etree.XPath, help='The XPath to the nodes to be dumped.\n' 'Defaults to the root node.') namespace = parser.parse_args(args) return namespace.action(namespace) if __name__ == '__main__': from sys import argv, stdin, stdout, stderr cli(argv[1:], stdin, stdout, stderr)
intuited/xmlearn
3fcc995cff776840d7418f923623115776b7821e
move outstream declaration from dump function into dump subcommand defaults
diff --git a/__init__.py b/__init__.py index ab1ebca..b2d49cb 100755 --- a/__init__.py +++ b/__init__.py @@ -1,291 +1,290 @@ #!/usr/bin/env python """Library and CLI for learning about XML formats.""" from lxml import etree class Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. ruleset: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. outstream: a stream to which the dump will be written. For now, this function is just useful for sussing out the shape of the XML. """ # TODO: write doctest examples # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'full': {None: {'recurse': True}}} default_ruleset = 'full' from sys import stdout outstream = stdout from pprint import PrettyPrinter pformat = PrettyPrinter(indent=2).pformat # Some more defaults. maxdepth = None width = 80 # This should maybe be moved into the CLI. @classmethod def print_rulesets(cls, ruleset=None, outstream=None, format=pformat, verbose=False): """Output ruleset information. If a `ruleset` is given, that ruleset's rules are output. If no `ruleset` is given, a list of rulesets is output. The `verbose` option will cause full ruleset information to be given in the list of rulesets. `format` can be used to specify a different formatting function. """ outstream = outstream if outstream else cls.outstream if ruleset: outstream.write(format(cls.rulesets[ruleset])) else: if verbose: outstream.write(format(cls.rulesets)) else: outstream.writelines("\n".join(cls.rulesets.keys())) outstream.write("\n") def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `ruleset`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `outstream`, `maxdepth`, and `ruleset` object attributes can be overridden without modifying the object. If `ruleset` is not given, `self`'s default ruleset is used. I suspect that actually using XSLT would be a better way to do this. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) # Pull variables from kwargs or self maxdepth, outstream = (kwargs.pop(v, getattr(self, v)) for v in ('maxdepth', 'outstream')) ruleset = kwargs.pop('ruleset', getattr(self, 'ruleset', self.default_ruleset)) if isinstance(ruleset, basestring): ruleset = self.rulesets[ruleset] assert isinstance(ruleset, Mapping) def _dump(element, depth=0): for rule in ruleset.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) outstream.write(self.format_element(element, depth, **kwargs)) outstream.write("\n") if recurse: if maxdepth is None or maxdepth > depth: for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) def iter_unique_child_tags(self, root, tag): """Iterates through unique child tags for all instances of `tag`. Iteration starts at `root`. """ found_child_tags = set() instances = root.iterdescendants(tag) from itertools import chain child_nodes = chain.from_iterable(i.getchildren() for i in instances) child_tags = (n.tag for n in child_nodes) for t in child_tags: if t not in found_child_tags: found_child_tags.add(t) yield t def iter_tag_list(self, root): """List all unique tags at and under the `root` node.""" found_tags = set() tags = (n.tag for n in root.iterdescendants() if hasattr(n, 'tag')) for t in tags: if t not in found_tags: found_tags.add(t) yield t def build_tag_graph(self, root): """Build a python-graph graph of the tag relationships.""" from pygraph.classes.digraph import digraph g = digraph() tags = list(self.iter_tag_list(root)) g.add_nodes(tags) for parent in tags: for child in self.iter_unique_child_tags(root, parent): g.add_edge((parent, child)) return g def write_graph(self, graph, filename, format='png'): """Write a python-graph graph as an image. `format` can be any of those supported by pydot.Dot.write(). """ from pygraph.readwrite.dot import write dotdata = write(graph) from pydot import graph_from_dot_data dotgraph = graph_from_dot_data(dotdata) dotgraph.write(filename, format=format) def write_tag_graph(self, root, filename, format='png'): graph = self.build_tag_graph(root) self.write_graph(graph, filename, format=format) # TODO: refactor this as a class. # TODO: make the dump command's `path` option a general one. def cli(args, in_, out, err, Dumper=Dumper): """Provide a command-line interface to the module functionality. Dumper: xmlearn.Dumper or subclass. Called in response to the `dump` subcommand. Note that this should be the *class*, not an instantiation of it. args: the arguments to be parsed. in_, out, err: open input/output/error files. """ from argparse import ArgumentParser, FileType, Action def call_function(ns): """Calls `ns.function`, passing arguments as determined by `ns`. Attributes of `ns` which are listed in `ns.kw_from_ns` are added to the set of keyword arguments passed to `ns.function`. """ kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if key in ns.kw_from_ns) return ns.function(**kwargs) def dump(ns): """Initializes a Dumper with values from the namespace `ns`. False values are filtered out. Calls its `dump` method, sending output to `out`. """ - kw_from_ns = ['width', 'maxdepth', 'ruleset'] + kw_from_ns = ['width', 'maxdepth', 'ruleset', 'outstream'] kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if value is not None) - kwargs['outstream'] = out dumper = Dumper(**kwargs) root = etree.parse(ns.infile).getroot() return [dumper.dump(e) for e in ns.path(root)] def list_rulesets(ns): return Dumper.print_rulesets(ruleset=ns.ruleset, verbose=ns.verbose) parser = ArgumentParser() parser.add_argument('-i', '--infile', type=FileType, default=in_, help='The XML file to learn about.\n' 'Defaults to stdin.') class ListRulesetsAction(Action): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, 'action', list_rulesets) setattr(namespace, 'ruleset', values) subparsers = parser.add_subparsers(title='subcommands') p_dump = subparsers.add_parser('dump', help='Dump xml data according to a set of rules.', description='Dump xml data according to a set of rules.') - p_dump.set_defaults(action=dump) + p_dump.set_defaults(action=dump, outstream=out) p_dump.add_argument('-l', '--list-rulesets', metavar='RULESET', nargs='?', action=ListRulesetsAction, help='Get a list of rulesets ' 'or information about a particular ruleset') p_dump.add_argument('-r', '--ruleset', choices=Dumper.rulesets.keys(), default=Dumper.default_ruleset, help='Which set of rules to apply.\nDefaults to "{0}".' .format(Dumper.default_ruleset)) p_dump.add_argument('-d', '--maxdepth', type=int, help='How many levels to dump.') # TODO: set default width to console width p_dump.add_argument('-w', '--width', type=int, help='The output width of the dump.') p_dump.add_argument('-v', '--verbose', action='store_true', help='Enable verbose ruleset list.\n' 'Only useful with `-l`.') p_dump.add_argument(dest='path', nargs='?', default='/*', type=etree.XPath, help='The XPath to the nodes to be dumped.\n' 'Defaults to the root node.') namespace = parser.parse_args(args) return namespace.action(namespace) if __name__ == '__main__': from sys import argv, stdin, stdout, stderr cli(argv[1:], stdin, stdout, stderr)
intuited/xmlearn
54170bca6e8d5de0f20a571c16ae0b582897a5ad
remove completed TODO about using custom Actions
diff --git a/__init__.py b/__init__.py index 755b5be..ab1ebca 100755 --- a/__init__.py +++ b/__init__.py @@ -1,293 +1,291 @@ #!/usr/bin/env python """Library and CLI for learning about XML formats.""" from lxml import etree class Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. ruleset: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. outstream: a stream to which the dump will be written. For now, this function is just useful for sussing out the shape of the XML. """ # TODO: write doctest examples # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'full': {None: {'recurse': True}}} default_ruleset = 'full' from sys import stdout outstream = stdout from pprint import PrettyPrinter pformat = PrettyPrinter(indent=2).pformat # Some more defaults. maxdepth = None width = 80 # This should maybe be moved into the CLI. @classmethod def print_rulesets(cls, ruleset=None, outstream=None, format=pformat, verbose=False): """Output ruleset information. If a `ruleset` is given, that ruleset's rules are output. If no `ruleset` is given, a list of rulesets is output. The `verbose` option will cause full ruleset information to be given in the list of rulesets. `format` can be used to specify a different formatting function. """ outstream = outstream if outstream else cls.outstream if ruleset: outstream.write(format(cls.rulesets[ruleset])) else: if verbose: outstream.write(format(cls.rulesets)) else: outstream.writelines("\n".join(cls.rulesets.keys())) outstream.write("\n") def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `ruleset`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `outstream`, `maxdepth`, and `ruleset` object attributes can be overridden without modifying the object. If `ruleset` is not given, `self`'s default ruleset is used. I suspect that actually using XSLT would be a better way to do this. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) # Pull variables from kwargs or self maxdepth, outstream = (kwargs.pop(v, getattr(self, v)) for v in ('maxdepth', 'outstream')) ruleset = kwargs.pop('ruleset', getattr(self, 'ruleset', self.default_ruleset)) if isinstance(ruleset, basestring): ruleset = self.rulesets[ruleset] assert isinstance(ruleset, Mapping) def _dump(element, depth=0): for rule in ruleset.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) outstream.write(self.format_element(element, depth, **kwargs)) outstream.write("\n") if recurse: if maxdepth is None or maxdepth > depth: for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) def iter_unique_child_tags(self, root, tag): """Iterates through unique child tags for all instances of `tag`. Iteration starts at `root`. """ found_child_tags = set() instances = root.iterdescendants(tag) from itertools import chain child_nodes = chain.from_iterable(i.getchildren() for i in instances) child_tags = (n.tag for n in child_nodes) for t in child_tags: if t not in found_child_tags: found_child_tags.add(t) yield t def iter_tag_list(self, root): """List all unique tags at and under the `root` node.""" found_tags = set() tags = (n.tag for n in root.iterdescendants() if hasattr(n, 'tag')) for t in tags: if t not in found_tags: found_tags.add(t) yield t def build_tag_graph(self, root): """Build a python-graph graph of the tag relationships.""" from pygraph.classes.digraph import digraph g = digraph() tags = list(self.iter_tag_list(root)) g.add_nodes(tags) for parent in tags: for child in self.iter_unique_child_tags(root, parent): g.add_edge((parent, child)) return g def write_graph(self, graph, filename, format='png'): """Write a python-graph graph as an image. `format` can be any of those supported by pydot.Dot.write(). """ from pygraph.readwrite.dot import write dotdata = write(graph) from pydot import graph_from_dot_data dotgraph = graph_from_dot_data(dotdata) dotgraph.write(filename, format=format) def write_tag_graph(self, root, filename, format='png'): graph = self.build_tag_graph(root) self.write_graph(graph, filename, format=format) # TODO: refactor this as a class. # TODO: make the dump command's `path` option a general one. def cli(args, in_, out, err, Dumper=Dumper): """Provide a command-line interface to the module functionality. Dumper: xmlearn.Dumper or subclass. Called in response to the `dump` subcommand. Note that this should be the *class*, not an instantiation of it. args: the arguments to be parsed. in_, out, err: open input/output/error files. """ from argparse import ArgumentParser, FileType, Action def call_function(ns): """Calls `ns.function`, passing arguments as determined by `ns`. Attributes of `ns` which are listed in `ns.kw_from_ns` are added to the set of keyword arguments passed to `ns.function`. """ kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if key in ns.kw_from_ns) return ns.function(**kwargs) def dump(ns): """Initializes a Dumper with values from the namespace `ns`. False values are filtered out. Calls its `dump` method, sending output to `out`. """ kw_from_ns = ['width', 'maxdepth', 'ruleset'] kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if value is not None) kwargs['outstream'] = out dumper = Dumper(**kwargs) root = etree.parse(ns.infile).getroot() return [dumper.dump(e) for e in ns.path(root)] def list_rulesets(ns): return Dumper.print_rulesets(ruleset=ns.ruleset, verbose=ns.verbose) parser = ArgumentParser() parser.add_argument('-i', '--infile', type=FileType, default=in_, help='The XML file to learn about.\n' 'Defaults to stdin.') class ListRulesetsAction(Action): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, 'action', list_rulesets) setattr(namespace, 'ruleset', values) subparsers = parser.add_subparsers(title='subcommands') p_dump = subparsers.add_parser('dump', help='Dump xml data according to a set of rules.', description='Dump xml data according to a set of rules.') p_dump.set_defaults(action=dump) - # TODO: rework argparsing (again) to use custom Actions. - p_dump.add_argument('-l', '--list-rulesets', metavar='RULESET', nargs='?', action=ListRulesetsAction, help='Get a list of rulesets ' 'or information about a particular ruleset') p_dump.add_argument('-r', '--ruleset', choices=Dumper.rulesets.keys(), default=Dumper.default_ruleset, help='Which set of rules to apply.\nDefaults to "{0}".' .format(Dumper.default_ruleset)) p_dump.add_argument('-d', '--maxdepth', type=int, help='How many levels to dump.') # TODO: set default width to console width p_dump.add_argument('-w', '--width', type=int, help='The output width of the dump.') p_dump.add_argument('-v', '--verbose', action='store_true', help='Enable verbose ruleset list.\n' 'Only useful with `-l`.') p_dump.add_argument(dest='path', nargs='?', default='/*', type=etree.XPath, help='The XPath to the nodes to be dumped.\n' 'Defaults to the root node.') namespace = parser.parse_args(args) return namespace.action(namespace) if __name__ == '__main__': from sys import argv, stdin, stdout, stderr cli(argv[1:], stdin, stdout, stderr)
intuited/xmlearn
ddddfb5c2df71e7a505b86874d8c23428cdbdbbb
moved XPath creation into argument parsing
diff --git a/__init__.py b/__init__.py index 45a683a..755b5be 100755 --- a/__init__.py +++ b/__init__.py @@ -1,298 +1,293 @@ #!/usr/bin/env python """Library and CLI for learning about XML formats.""" from lxml import etree class Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. ruleset: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. outstream: a stream to which the dump will be written. For now, this function is just useful for sussing out the shape of the XML. """ # TODO: write doctest examples # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'full': {None: {'recurse': True}}} default_ruleset = 'full' from sys import stdout outstream = stdout from pprint import PrettyPrinter pformat = PrettyPrinter(indent=2).pformat # Some more defaults. maxdepth = None width = 80 # This should maybe be moved into the CLI. @classmethod def print_rulesets(cls, ruleset=None, outstream=None, format=pformat, verbose=False): """Output ruleset information. If a `ruleset` is given, that ruleset's rules are output. If no `ruleset` is given, a list of rulesets is output. The `verbose` option will cause full ruleset information to be given in the list of rulesets. `format` can be used to specify a different formatting function. """ outstream = outstream if outstream else cls.outstream if ruleset: outstream.write(format(cls.rulesets[ruleset])) else: if verbose: outstream.write(format(cls.rulesets)) else: outstream.writelines("\n".join(cls.rulesets.keys())) outstream.write("\n") def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `ruleset`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `outstream`, `maxdepth`, and `ruleset` object attributes can be overridden without modifying the object. If `ruleset` is not given, `self`'s default ruleset is used. I suspect that actually using XSLT would be a better way to do this. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) # Pull variables from kwargs or self maxdepth, outstream = (kwargs.pop(v, getattr(self, v)) for v in ('maxdepth', 'outstream')) ruleset = kwargs.pop('ruleset', getattr(self, 'ruleset', self.default_ruleset)) if isinstance(ruleset, basestring): ruleset = self.rulesets[ruleset] assert isinstance(ruleset, Mapping) def _dump(element, depth=0): for rule in ruleset.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) outstream.write(self.format_element(element, depth, **kwargs)) outstream.write("\n") if recurse: if maxdepth is None or maxdepth > depth: for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) def iter_unique_child_tags(self, root, tag): """Iterates through unique child tags for all instances of `tag`. Iteration starts at `root`. """ found_child_tags = set() instances = root.iterdescendants(tag) from itertools import chain child_nodes = chain.from_iterable(i.getchildren() for i in instances) child_tags = (n.tag for n in child_nodes) for t in child_tags: if t not in found_child_tags: found_child_tags.add(t) yield t def iter_tag_list(self, root): """List all unique tags at and under the `root` node.""" found_tags = set() tags = (n.tag for n in root.iterdescendants() if hasattr(n, 'tag')) for t in tags: if t not in found_tags: found_tags.add(t) yield t def build_tag_graph(self, root): """Build a python-graph graph of the tag relationships.""" from pygraph.classes.digraph import digraph g = digraph() tags = list(self.iter_tag_list(root)) g.add_nodes(tags) for parent in tags: for child in self.iter_unique_child_tags(root, parent): g.add_edge((parent, child)) return g def write_graph(self, graph, filename, format='png'): """Write a python-graph graph as an image. `format` can be any of those supported by pydot.Dot.write(). """ from pygraph.readwrite.dot import write dotdata = write(graph) from pydot import graph_from_dot_data dotgraph = graph_from_dot_data(dotdata) dotgraph.write(filename, format=format) def write_tag_graph(self, root, filename, format='png'): graph = self.build_tag_graph(root) self.write_graph(graph, filename, format=format) # TODO: refactor this as a class. # TODO: make the dump command's `path` option a general one. def cli(args, in_, out, err, Dumper=Dumper): """Provide a command-line interface to the module functionality. Dumper: xmlearn.Dumper or subclass. Called in response to the `dump` subcommand. Note that this should be the *class*, not an instantiation of it. args: the arguments to be parsed. in_, out, err: open input/output/error files. """ from argparse import ArgumentParser, FileType, Action def call_function(ns): """Calls `ns.function`, passing arguments as determined by `ns`. Attributes of `ns` which are listed in `ns.kw_from_ns` are added to the set of keyword arguments passed to `ns.function`. """ kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if key in ns.kw_from_ns) return ns.function(**kwargs) def dump(ns): """Initializes a Dumper with values from the namespace `ns`. False values are filtered out. Calls its `dump` method, sending output to `out`. """ kw_from_ns = ['width', 'maxdepth', 'ruleset'] kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if value is not None) kwargs['outstream'] = out dumper = Dumper(**kwargs) - from lxml.etree import parse, XPath - root = parse(ns.infile).getroot() - if ns.path: - path = XPath(ns.path) - return [dumper.dump(e) for e in path(root)] - else: - return dumper.dump(root) + root = etree.parse(ns.infile).getroot() + return [dumper.dump(e) for e in ns.path(root)] def list_rulesets(ns): return Dumper.print_rulesets(ruleset=ns.ruleset, verbose=ns.verbose) parser = ArgumentParser() parser.add_argument('-i', '--infile', type=FileType, default=in_, help='The XML file to learn about.\n' 'Defaults to stdin.') class ListRulesetsAction(Action): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, 'action', list_rulesets) setattr(namespace, 'ruleset', values) subparsers = parser.add_subparsers(title='subcommands') p_dump = subparsers.add_parser('dump', help='Dump xml data according to a set of rules.', description='Dump xml data according to a set of rules.') p_dump.set_defaults(action=dump) # TODO: rework argparsing (again) to use custom Actions. p_dump.add_argument('-l', '--list-rulesets', metavar='RULESET', nargs='?', action=ListRulesetsAction, help='Get a list of rulesets ' 'or information about a particular ruleset') p_dump.add_argument('-r', '--ruleset', choices=Dumper.rulesets.keys(), default=Dumper.default_ruleset, help='Which set of rules to apply.\nDefaults to "{0}".' .format(Dumper.default_ruleset)) p_dump.add_argument('-d', '--maxdepth', type=int, help='How many levels to dump.') # TODO: set default width to console width p_dump.add_argument('-w', '--width', type=int, help='The output width of the dump.') p_dump.add_argument('-v', '--verbose', action='store_true', help='Enable verbose ruleset list.\n' 'Only useful with `-l`.') - p_dump.add_argument(dest='path', nargs='?', default=None, - help='The XPath to the node to be dumped.\n' + p_dump.add_argument(dest='path', nargs='?', default='/*', type=etree.XPath, + help='The XPath to the nodes to be dumped.\n' 'Defaults to the root node.') namespace = parser.parse_args(args) return namespace.action(namespace) if __name__ == '__main__': from sys import argv, stdin, stdout, stderr cli(argv[1:], stdin, stdout, stderr)
intuited/xmlearn
d95464cc7a67ea21a33ae45e6249f68910a2d19a
cleanup extraneous parentheses
diff --git a/__init__.py b/__init__.py index 0acbe8c..45a683a 100755 --- a/__init__.py +++ b/__init__.py @@ -1,298 +1,298 @@ #!/usr/bin/env python """Library and CLI for learning about XML formats.""" from lxml import etree class Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. ruleset: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. outstream: a stream to which the dump will be written. For now, this function is just useful for sussing out the shape of the XML. """ # TODO: write doctest examples # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'full': {None: {'recurse': True}}} default_ruleset = 'full' from sys import stdout outstream = stdout from pprint import PrettyPrinter pformat = PrettyPrinter(indent=2).pformat # Some more defaults. maxdepth = None width = 80 # This should maybe be moved into the CLI. @classmethod def print_rulesets(cls, ruleset=None, outstream=None, format=pformat, verbose=False): """Output ruleset information. If a `ruleset` is given, that ruleset's rules are output. If no `ruleset` is given, a list of rulesets is output. The `verbose` option will cause full ruleset information to be given in the list of rulesets. `format` can be used to specify a different formatting function. """ outstream = outstream if outstream else cls.outstream if ruleset: outstream.write(format(cls.rulesets[ruleset])) else: if verbose: outstream.write(format(cls.rulesets)) else: outstream.writelines("\n".join(cls.rulesets.keys())) outstream.write("\n") def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `ruleset`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `outstream`, `maxdepth`, and `ruleset` object attributes can be overridden without modifying the object. If `ruleset` is not given, `self`'s default ruleset is used. I suspect that actually using XSLT would be a better way to do this. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) # Pull variables from kwargs or self maxdepth, outstream = (kwargs.pop(v, getattr(self, v)) for v in ('maxdepth', 'outstream')) ruleset = kwargs.pop('ruleset', getattr(self, 'ruleset', self.default_ruleset)) if isinstance(ruleset, basestring): ruleset = self.rulesets[ruleset] assert isinstance(ruleset, Mapping) def _dump(element, depth=0): for rule in ruleset.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) outstream.write(self.format_element(element, depth, **kwargs)) outstream.write("\n") if recurse: - if (maxdepth is None or maxdepth > depth): + if maxdepth is None or maxdepth > depth: for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) def iter_unique_child_tags(self, root, tag): """Iterates through unique child tags for all instances of `tag`. Iteration starts at `root`. """ found_child_tags = set() instances = root.iterdescendants(tag) from itertools import chain child_nodes = chain.from_iterable(i.getchildren() for i in instances) child_tags = (n.tag for n in child_nodes) for t in child_tags: if t not in found_child_tags: found_child_tags.add(t) yield t def iter_tag_list(self, root): """List all unique tags at and under the `root` node.""" found_tags = set() tags = (n.tag for n in root.iterdescendants() if hasattr(n, 'tag')) for t in tags: if t not in found_tags: found_tags.add(t) yield t def build_tag_graph(self, root): """Build a python-graph graph of the tag relationships.""" from pygraph.classes.digraph import digraph g = digraph() tags = list(self.iter_tag_list(root)) g.add_nodes(tags) for parent in tags: for child in self.iter_unique_child_tags(root, parent): g.add_edge((parent, child)) return g def write_graph(self, graph, filename, format='png'): """Write a python-graph graph as an image. `format` can be any of those supported by pydot.Dot.write(). """ from pygraph.readwrite.dot import write dotdata = write(graph) from pydot import graph_from_dot_data dotgraph = graph_from_dot_data(dotdata) dotgraph.write(filename, format=format) def write_tag_graph(self, root, filename, format='png'): graph = self.build_tag_graph(root) self.write_graph(graph, filename, format=format) # TODO: refactor this as a class. # TODO: make the dump command's `path` option a general one. def cli(args, in_, out, err, Dumper=Dumper): """Provide a command-line interface to the module functionality. Dumper: xmlearn.Dumper or subclass. Called in response to the `dump` subcommand. Note that this should be the *class*, not an instantiation of it. args: the arguments to be parsed. in_, out, err: open input/output/error files. """ from argparse import ArgumentParser, FileType, Action def call_function(ns): """Calls `ns.function`, passing arguments as determined by `ns`. Attributes of `ns` which are listed in `ns.kw_from_ns` are added to the set of keyword arguments passed to `ns.function`. """ kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if key in ns.kw_from_ns) return ns.function(**kwargs) def dump(ns): """Initializes a Dumper with values from the namespace `ns`. False values are filtered out. Calls its `dump` method, sending output to `out`. """ kw_from_ns = ['width', 'maxdepth', 'ruleset'] kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if value is not None) kwargs['outstream'] = out dumper = Dumper(**kwargs) from lxml.etree import parse, XPath root = parse(ns.infile).getroot() if ns.path: path = XPath(ns.path) return [dumper.dump(e) for e in path(root)] else: return dumper.dump(root) def list_rulesets(ns): return Dumper.print_rulesets(ruleset=ns.ruleset, verbose=ns.verbose) parser = ArgumentParser() parser.add_argument('-i', '--infile', type=FileType, default=in_, help='The XML file to learn about.\n' 'Defaults to stdin.') class ListRulesetsAction(Action): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, 'action', list_rulesets) setattr(namespace, 'ruleset', values) subparsers = parser.add_subparsers(title='subcommands') p_dump = subparsers.add_parser('dump', help='Dump xml data according to a set of rules.', description='Dump xml data according to a set of rules.') p_dump.set_defaults(action=dump) # TODO: rework argparsing (again) to use custom Actions. p_dump.add_argument('-l', '--list-rulesets', metavar='RULESET', nargs='?', action=ListRulesetsAction, help='Get a list of rulesets ' 'or information about a particular ruleset') p_dump.add_argument('-r', '--ruleset', choices=Dumper.rulesets.keys(), default=Dumper.default_ruleset, help='Which set of rules to apply.\nDefaults to "{0}".' .format(Dumper.default_ruleset)) p_dump.add_argument('-d', '--maxdepth', type=int, help='How many levels to dump.') # TODO: set default width to console width p_dump.add_argument('-w', '--width', type=int, help='The output width of the dump.') p_dump.add_argument('-v', '--verbose', action='store_true', help='Enable verbose ruleset list.\n' 'Only useful with `-l`.') p_dump.add_argument(dest='path', nargs='?', default=None, help='The XPath to the node to be dumped.\n' 'Defaults to the root node.') namespace = parser.parse_args(args) return namespace.action(namespace) if __name__ == '__main__': from sys import argv, stdin, stdout, stderr cli(argv[1:], stdin, stdout, stderr)
intuited/xmlearn
453b4c59fb5da4857550ac395fc7f08840552fe2
fix bug that was preventing the `-w 0` switch from working.
diff --git a/__init__.py b/__init__.py index bcc07b7..0acbe8c 100755 --- a/__init__.py +++ b/__init__.py @@ -1,298 +1,298 @@ #!/usr/bin/env python """Library and CLI for learning about XML formats.""" from lxml import etree class Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. ruleset: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. outstream: a stream to which the dump will be written. For now, this function is just useful for sussing out the shape of the XML. """ # TODO: write doctest examples # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'full': {None: {'recurse': True}}} default_ruleset = 'full' from sys import stdout outstream = stdout from pprint import PrettyPrinter pformat = PrettyPrinter(indent=2).pformat # Some more defaults. maxdepth = None width = 80 # This should maybe be moved into the CLI. @classmethod def print_rulesets(cls, ruleset=None, outstream=None, format=pformat, verbose=False): """Output ruleset information. If a `ruleset` is given, that ruleset's rules are output. If no `ruleset` is given, a list of rulesets is output. The `verbose` option will cause full ruleset information to be given in the list of rulesets. `format` can be used to specify a different formatting function. """ outstream = outstream if outstream else cls.outstream if ruleset: outstream.write(format(cls.rulesets[ruleset])) else: if verbose: outstream.write(format(cls.rulesets)) else: outstream.writelines("\n".join(cls.rulesets.keys())) outstream.write("\n") def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `ruleset`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `outstream`, `maxdepth`, and `ruleset` object attributes can be overridden without modifying the object. If `ruleset` is not given, `self`'s default ruleset is used. I suspect that actually using XSLT would be a better way to do this. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) # Pull variables from kwargs or self maxdepth, outstream = (kwargs.pop(v, getattr(self, v)) for v in ('maxdepth', 'outstream')) ruleset = kwargs.pop('ruleset', getattr(self, 'ruleset', self.default_ruleset)) if isinstance(ruleset, basestring): ruleset = self.rulesets[ruleset] assert isinstance(ruleset, Mapping) def _dump(element, depth=0): for rule in ruleset.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) outstream.write(self.format_element(element, depth, **kwargs)) outstream.write("\n") if recurse: if (maxdepth is None or maxdepth > depth): for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) def iter_unique_child_tags(self, root, tag): """Iterates through unique child tags for all instances of `tag`. Iteration starts at `root`. """ found_child_tags = set() instances = root.iterdescendants(tag) from itertools import chain child_nodes = chain.from_iterable(i.getchildren() for i in instances) child_tags = (n.tag for n in child_nodes) for t in child_tags: if t not in found_child_tags: found_child_tags.add(t) yield t def iter_tag_list(self, root): """List all unique tags at and under the `root` node.""" found_tags = set() tags = (n.tag for n in root.iterdescendants() if hasattr(n, 'tag')) for t in tags: if t not in found_tags: found_tags.add(t) yield t def build_tag_graph(self, root): """Build a python-graph graph of the tag relationships.""" from pygraph.classes.digraph import digraph g = digraph() tags = list(self.iter_tag_list(root)) g.add_nodes(tags) for parent in tags: for child in self.iter_unique_child_tags(root, parent): g.add_edge((parent, child)) return g def write_graph(self, graph, filename, format='png'): """Write a python-graph graph as an image. `format` can be any of those supported by pydot.Dot.write(). """ from pygraph.readwrite.dot import write dotdata = write(graph) from pydot import graph_from_dot_data dotgraph = graph_from_dot_data(dotdata) dotgraph.write(filename, format=format) def write_tag_graph(self, root, filename, format='png'): graph = self.build_tag_graph(root) self.write_graph(graph, filename, format=format) # TODO: refactor this as a class. # TODO: make the dump command's `path` option a general one. def cli(args, in_, out, err, Dumper=Dumper): """Provide a command-line interface to the module functionality. Dumper: xmlearn.Dumper or subclass. Called in response to the `dump` subcommand. Note that this should be the *class*, not an instantiation of it. args: the arguments to be parsed. in_, out, err: open input/output/error files. """ from argparse import ArgumentParser, FileType, Action def call_function(ns): """Calls `ns.function`, passing arguments as determined by `ns`. Attributes of `ns` which are listed in `ns.kw_from_ns` are added to the set of keyword arguments passed to `ns.function`. """ kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if key in ns.kw_from_ns) return ns.function(**kwargs) def dump(ns): """Initializes a Dumper with values from the namespace `ns`. False values are filtered out. Calls its `dump` method, sending output to `out`. """ kw_from_ns = ['width', 'maxdepth', 'ruleset'] kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() - if value) + if value is not None) kwargs['outstream'] = out dumper = Dumper(**kwargs) from lxml.etree import parse, XPath root = parse(ns.infile).getroot() if ns.path: path = XPath(ns.path) return [dumper.dump(e) for e in path(root)] else: return dumper.dump(root) def list_rulesets(ns): return Dumper.print_rulesets(ruleset=ns.ruleset, verbose=ns.verbose) parser = ArgumentParser() parser.add_argument('-i', '--infile', type=FileType, default=in_, help='The XML file to learn about.\n' 'Defaults to stdin.') class ListRulesetsAction(Action): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, 'action', list_rulesets) setattr(namespace, 'ruleset', values) subparsers = parser.add_subparsers(title='subcommands') p_dump = subparsers.add_parser('dump', help='Dump xml data according to a set of rules.', description='Dump xml data according to a set of rules.') p_dump.set_defaults(action=dump) # TODO: rework argparsing (again) to use custom Actions. p_dump.add_argument('-l', '--list-rulesets', metavar='RULESET', nargs='?', action=ListRulesetsAction, help='Get a list of rulesets ' 'or information about a particular ruleset') p_dump.add_argument('-r', '--ruleset', choices=Dumper.rulesets.keys(), default=Dumper.default_ruleset, help='Which set of rules to apply.\nDefaults to "{0}".' .format(Dumper.default_ruleset)) p_dump.add_argument('-d', '--maxdepth', type=int, help='How many levels to dump.') # TODO: set default width to console width p_dump.add_argument('-w', '--width', type=int, help='The output width of the dump.') p_dump.add_argument('-v', '--verbose', action='store_true', help='Enable verbose ruleset list.\n' 'Only useful with `-l`.') p_dump.add_argument(dest='path', nargs='?', default=None, help='The XPath to the node to be dumped.\n' 'Defaults to the root node.') namespace = parser.parse_args(args) return namespace.action(namespace) if __name__ == '__main__': from sys import argv, stdin, stdout, stderr cli(argv[1:], stdin, stdout, stderr)
intuited/xmlearn
3253315285c8847df53c6be1815ab60f89f5311c
remove pointless TODO
diff --git a/__init__.py b/__init__.py index ace2a65..bcc07b7 100755 --- a/__init__.py +++ b/__init__.py @@ -1,299 +1,298 @@ #!/usr/bin/env python """Library and CLI for learning about XML formats.""" from lxml import etree class Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. ruleset: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. outstream: a stream to which the dump will be written. For now, this function is just useful for sussing out the shape of the XML. """ # TODO: write doctest examples # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'full': {None: {'recurse': True}}} default_ruleset = 'full' from sys import stdout outstream = stdout from pprint import PrettyPrinter pformat = PrettyPrinter(indent=2).pformat # Some more defaults. maxdepth = None width = 80 # This should maybe be moved into the CLI. @classmethod def print_rulesets(cls, ruleset=None, outstream=None, format=pformat, verbose=False): """Output ruleset information. If a `ruleset` is given, that ruleset's rules are output. If no `ruleset` is given, a list of rulesets is output. The `verbose` option will cause full ruleset information to be given in the list of rulesets. `format` can be used to specify a different formatting function. """ outstream = outstream if outstream else cls.outstream if ruleset: outstream.write(format(cls.rulesets[ruleset])) else: if verbose: outstream.write(format(cls.rulesets)) else: outstream.writelines("\n".join(cls.rulesets.keys())) outstream.write("\n") def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `ruleset`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `outstream`, `maxdepth`, and `ruleset` object attributes can be overridden without modifying the object. If `ruleset` is not given, `self`'s default ruleset is used. I suspect that actually using XSLT would be a better way to do this. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) # Pull variables from kwargs or self maxdepth, outstream = (kwargs.pop(v, getattr(self, v)) for v in ('maxdepth', 'outstream')) ruleset = kwargs.pop('ruleset', getattr(self, 'ruleset', self.default_ruleset)) if isinstance(ruleset, basestring): ruleset = self.rulesets[ruleset] assert isinstance(ruleset, Mapping) def _dump(element, depth=0): for rule in ruleset.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) outstream.write(self.format_element(element, depth, **kwargs)) outstream.write("\n") if recurse: if (maxdepth is None or maxdepth > depth): for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) def iter_unique_child_tags(self, root, tag): """Iterates through unique child tags for all instances of `tag`. Iteration starts at `root`. """ found_child_tags = set() instances = root.iterdescendants(tag) from itertools import chain child_nodes = chain.from_iterable(i.getchildren() for i in instances) child_tags = (n.tag for n in child_nodes) for t in child_tags: if t not in found_child_tags: found_child_tags.add(t) yield t def iter_tag_list(self, root): """List all unique tags at and under the `root` node.""" found_tags = set() tags = (n.tag for n in root.iterdescendants() if hasattr(n, 'tag')) for t in tags: if t not in found_tags: found_tags.add(t) yield t def build_tag_graph(self, root): """Build a python-graph graph of the tag relationships.""" from pygraph.classes.digraph import digraph g = digraph() tags = list(self.iter_tag_list(root)) g.add_nodes(tags) for parent in tags: for child in self.iter_unique_child_tags(root, parent): g.add_edge((parent, child)) return g def write_graph(self, graph, filename, format='png'): """Write a python-graph graph as an image. `format` can be any of those supported by pydot.Dot.write(). """ from pygraph.readwrite.dot import write dotdata = write(graph) from pydot import graph_from_dot_data dotgraph = graph_from_dot_data(dotdata) dotgraph.write(filename, format=format) def write_tag_graph(self, root, filename, format='png'): graph = self.build_tag_graph(root) self.write_graph(graph, filename, format=format) # TODO: refactor this as a class. # TODO: make the dump command's `path` option a general one. def cli(args, in_, out, err, Dumper=Dumper): """Provide a command-line interface to the module functionality. Dumper: xmlearn.Dumper or subclass. Called in response to the `dump` subcommand. Note that this should be the *class*, not an instantiation of it. args: the arguments to be parsed. in_, out, err: open input/output/error files. """ from argparse import ArgumentParser, FileType, Action def call_function(ns): """Calls `ns.function`, passing arguments as determined by `ns`. Attributes of `ns` which are listed in `ns.kw_from_ns` are added to the set of keyword arguments passed to `ns.function`. """ kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if key in ns.kw_from_ns) return ns.function(**kwargs) def dump(ns): """Initializes a Dumper with values from the namespace `ns`. False values are filtered out. Calls its `dump` method, sending output to `out`. """ kw_from_ns = ['width', 'maxdepth', 'ruleset'] kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if value) kwargs['outstream'] = out dumper = Dumper(**kwargs) from lxml.etree import parse, XPath root = parse(ns.infile).getroot() if ns.path: path = XPath(ns.path) return [dumper.dump(e) for e in path(root)] else: return dumper.dump(root) def list_rulesets(ns): return Dumper.print_rulesets(ruleset=ns.ruleset, verbose=ns.verbose) parser = ArgumentParser() parser.add_argument('-i', '--infile', type=FileType, default=in_, help='The XML file to learn about.\n' 'Defaults to stdin.') class ListRulesetsAction(Action): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, 'action', list_rulesets) setattr(namespace, 'ruleset', values) subparsers = parser.add_subparsers(title='subcommands') p_dump = subparsers.add_parser('dump', help='Dump xml data according to a set of rules.', description='Dump xml data according to a set of rules.') p_dump.set_defaults(action=dump) # TODO: rework argparsing (again) to use custom Actions. p_dump.add_argument('-l', '--list-rulesets', metavar='RULESET', nargs='?', action=ListRulesetsAction, help='Get a list of rulesets ' 'or information about a particular ruleset') - # TODO: make the required nature of -r depend on the presence of a ruleset p_dump.add_argument('-r', '--ruleset', choices=Dumper.rulesets.keys(), default=Dumper.default_ruleset, help='Which set of rules to apply.\nDefaults to "{0}".' .format(Dumper.default_ruleset)) p_dump.add_argument('-d', '--maxdepth', type=int, help='How many levels to dump.') # TODO: set default width to console width p_dump.add_argument('-w', '--width', type=int, help='The output width of the dump.') p_dump.add_argument('-v', '--verbose', action='store_true', help='Enable verbose ruleset list.\n' 'Only useful with `-l`.') p_dump.add_argument(dest='path', nargs='?', default=None, help='The XPath to the node to be dumped.\n' 'Defaults to the root node.') namespace = parser.parse_args(args) return namespace.action(namespace) if __name__ == '__main__': from sys import argv, stdin, stdout, stderr cli(argv[1:], stdin, stdout, stderr)
intuited/xmlearn
8a577adc5a8b030d0cfab33ba5ca04b61a61dd96
rework to use an Action subclass to handle ruleset listing.
diff --git a/__init__.py b/__init__.py index 24c03a5..ace2a65 100755 --- a/__init__.py +++ b/__init__.py @@ -1,293 +1,299 @@ #!/usr/bin/env python """Library and CLI for learning about XML formats.""" from lxml import etree class Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. ruleset: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. outstream: a stream to which the dump will be written. For now, this function is just useful for sussing out the shape of the XML. """ # TODO: write doctest examples # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'full': {None: {'recurse': True}}} default_ruleset = 'full' from sys import stdout outstream = stdout from pprint import PrettyPrinter pformat = PrettyPrinter(indent=2).pformat # Some more defaults. maxdepth = None width = 80 # This should maybe be moved into the CLI. @classmethod def print_rulesets(cls, ruleset=None, outstream=None, format=pformat, verbose=False): """Output ruleset information. If a `ruleset` is given, that ruleset's rules are output. If no `ruleset` is given, a list of rulesets is output. The `verbose` option will cause full ruleset information to be given in the list of rulesets. `format` can be used to specify a different formatting function. """ outstream = outstream if outstream else cls.outstream if ruleset: outstream.write(format(cls.rulesets[ruleset])) else: if verbose: outstream.write(format(cls.rulesets)) else: outstream.writelines("\n".join(cls.rulesets.keys())) outstream.write("\n") def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `ruleset`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `outstream`, `maxdepth`, and `ruleset` object attributes can be overridden without modifying the object. If `ruleset` is not given, `self`'s default ruleset is used. I suspect that actually using XSLT would be a better way to do this. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) # Pull variables from kwargs or self maxdepth, outstream = (kwargs.pop(v, getattr(self, v)) for v in ('maxdepth', 'outstream')) ruleset = kwargs.pop('ruleset', getattr(self, 'ruleset', self.default_ruleset)) if isinstance(ruleset, basestring): ruleset = self.rulesets[ruleset] assert isinstance(ruleset, Mapping) def _dump(element, depth=0): for rule in ruleset.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) outstream.write(self.format_element(element, depth, **kwargs)) outstream.write("\n") if recurse: if (maxdepth is None or maxdepth > depth): for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) def iter_unique_child_tags(self, root, tag): """Iterates through unique child tags for all instances of `tag`. Iteration starts at `root`. """ found_child_tags = set() instances = root.iterdescendants(tag) from itertools import chain child_nodes = chain.from_iterable(i.getchildren() for i in instances) child_tags = (n.tag for n in child_nodes) for t in child_tags: if t not in found_child_tags: found_child_tags.add(t) yield t def iter_tag_list(self, root): """List all unique tags at and under the `root` node.""" found_tags = set() tags = (n.tag for n in root.iterdescendants() if hasattr(n, 'tag')) for t in tags: if t not in found_tags: found_tags.add(t) yield t def build_tag_graph(self, root): """Build a python-graph graph of the tag relationships.""" from pygraph.classes.digraph import digraph g = digraph() tags = list(self.iter_tag_list(root)) g.add_nodes(tags) for parent in tags: for child in self.iter_unique_child_tags(root, parent): g.add_edge((parent, child)) return g def write_graph(self, graph, filename, format='png'): """Write a python-graph graph as an image. `format` can be any of those supported by pydot.Dot.write(). """ from pygraph.readwrite.dot import write dotdata = write(graph) from pydot import graph_from_dot_data dotgraph = graph_from_dot_data(dotdata) dotgraph.write(filename, format=format) def write_tag_graph(self, root, filename, format='png'): graph = self.build_tag_graph(root) self.write_graph(graph, filename, format=format) # TODO: refactor this as a class. # TODO: make the dump command's `path` option a general one. def cli(args, in_, out, err, Dumper=Dumper): """Provide a command-line interface to the module functionality. Dumper: xmlearn.Dumper or subclass. Called in response to the `dump` subcommand. Note that this should be the *class*, not an instantiation of it. args: the arguments to be parsed. in_, out, err: open input/output/error files. """ - from argparse import ArgumentParser, FileType + from argparse import ArgumentParser, FileType, Action def call_function(ns): """Calls `ns.function`, passing arguments as determined by `ns`. Attributes of `ns` which are listed in `ns.kw_from_ns` are added to the set of keyword arguments passed to `ns.function`. """ kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if key in ns.kw_from_ns) return ns.function(**kwargs) def dump(ns): """Initializes a Dumper with values from the namespace `ns`. False values are filtered out. Calls its `dump` method, sending output to `out`. """ - if ns.list is False: - kw_from_ns = ['width', 'maxdepth', 'ruleset'] - kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() - if value) - kwargs['outstream'] = out - dumper = Dumper(**kwargs) - from lxml.etree import parse, XPath - root = parse(ns.infile).getroot() - if ns.path: - path = XPath(ns.path) - return [dumper.dump(e) for e in path(root)] - else: - return dumper.dump(root) + kw_from_ns = ['width', 'maxdepth', 'ruleset'] + kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() + if value) + kwargs['outstream'] = out + dumper = Dumper(**kwargs) + from lxml.etree import parse, XPath + root = parse(ns.infile).getroot() + if ns.path: + path = XPath(ns.path) + return [dumper.dump(e) for e in path(root)] else: - return Dumper.print_rulesets(ruleset=ns.list, - verbose=ns.verbose) + return dumper.dump(root) + + def list_rulesets(ns): + return Dumper.print_rulesets(ruleset=ns.ruleset, + verbose=ns.verbose) + parser = ArgumentParser() parser.add_argument('-i', '--infile', type=FileType, default=in_, help='The XML file to learn about.\n' 'Defaults to stdin.') + class ListRulesetsAction(Action): + def __call__(self, parser, namespace, values, option_string=None): + setattr(namespace, 'action', list_rulesets) + setattr(namespace, 'ruleset', values) + subparsers = parser.add_subparsers(title='subcommands') p_dump = subparsers.add_parser('dump', help='Dump xml data according to a set of rules.', description='Dump xml data according to a set of rules.') p_dump.set_defaults(action=dump) # TODO: rework argparsing (again) to use custom Actions. p_dump.add_argument('-l', '--list-rulesets', metavar='RULESET', - nargs='?', default=False, dest='list', + nargs='?', action=ListRulesetsAction, help='Get a list of rulesets ' 'or information about a particular ruleset') # TODO: make the required nature of -r depend on the presence of a ruleset p_dump.add_argument('-r', '--ruleset', choices=Dumper.rulesets.keys(), default=Dumper.default_ruleset, help='Which set of rules to apply.\nDefaults to "{0}".' .format(Dumper.default_ruleset)) p_dump.add_argument('-d', '--maxdepth', type=int, help='How many levels to dump.') # TODO: set default width to console width p_dump.add_argument('-w', '--width', type=int, help='The output width of the dump.') p_dump.add_argument('-v', '--verbose', action='store_true', help='Enable verbose ruleset list.\n' 'Only useful with `-l`.') p_dump.add_argument(dest='path', nargs='?', default=None, help='The XPath to the node to be dumped.\n' 'Defaults to the root node.') namespace = parser.parse_args(args) return namespace.action(namespace) if __name__ == '__main__': from sys import argv, stdin, stdout, stderr cli(argv[1:], stdin, stdout, stderr)
intuited/xmlearn
a1c2a47cc13034af428f645aa02d5b8ffc2267fb
use subcommand defaults instead of action map
diff --git a/__init__.py b/__init__.py index a4bfc0a..24c03a5 100755 --- a/__init__.py +++ b/__init__.py @@ -1,306 +1,293 @@ #!/usr/bin/env python """Library and CLI for learning about XML formats.""" from lxml import etree class Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. ruleset: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. outstream: a stream to which the dump will be written. For now, this function is just useful for sussing out the shape of the XML. """ # TODO: write doctest examples # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'full': {None: {'recurse': True}}} default_ruleset = 'full' from sys import stdout outstream = stdout from pprint import PrettyPrinter pformat = PrettyPrinter(indent=2).pformat # Some more defaults. maxdepth = None width = 80 # This should maybe be moved into the CLI. @classmethod def print_rulesets(cls, ruleset=None, outstream=None, format=pformat, verbose=False): """Output ruleset information. If a `ruleset` is given, that ruleset's rules are output. If no `ruleset` is given, a list of rulesets is output. The `verbose` option will cause full ruleset information to be given in the list of rulesets. `format` can be used to specify a different formatting function. """ outstream = outstream if outstream else cls.outstream if ruleset: outstream.write(format(cls.rulesets[ruleset])) else: if verbose: outstream.write(format(cls.rulesets)) else: outstream.writelines("\n".join(cls.rulesets.keys())) outstream.write("\n") def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `ruleset`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `outstream`, `maxdepth`, and `ruleset` object attributes can be overridden without modifying the object. If `ruleset` is not given, `self`'s default ruleset is used. I suspect that actually using XSLT would be a better way to do this. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) # Pull variables from kwargs or self maxdepth, outstream = (kwargs.pop(v, getattr(self, v)) for v in ('maxdepth', 'outstream')) ruleset = kwargs.pop('ruleset', getattr(self, 'ruleset', self.default_ruleset)) if isinstance(ruleset, basestring): ruleset = self.rulesets[ruleset] assert isinstance(ruleset, Mapping) def _dump(element, depth=0): for rule in ruleset.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) outstream.write(self.format_element(element, depth, **kwargs)) outstream.write("\n") if recurse: if (maxdepth is None or maxdepth > depth): for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) def iter_unique_child_tags(self, root, tag): """Iterates through unique child tags for all instances of `tag`. Iteration starts at `root`. """ found_child_tags = set() instances = root.iterdescendants(tag) from itertools import chain child_nodes = chain.from_iterable(i.getchildren() for i in instances) child_tags = (n.tag for n in child_nodes) for t in child_tags: if t not in found_child_tags: found_child_tags.add(t) yield t def iter_tag_list(self, root): """List all unique tags at and under the `root` node.""" found_tags = set() tags = (n.tag for n in root.iterdescendants() if hasattr(n, 'tag')) for t in tags: if t not in found_tags: found_tags.add(t) yield t def build_tag_graph(self, root): """Build a python-graph graph of the tag relationships.""" from pygraph.classes.digraph import digraph g = digraph() tags = list(self.iter_tag_list(root)) g.add_nodes(tags) for parent in tags: for child in self.iter_unique_child_tags(root, parent): g.add_edge((parent, child)) return g def write_graph(self, graph, filename, format='png'): """Write a python-graph graph as an image. `format` can be any of those supported by pydot.Dot.write(). """ from pygraph.readwrite.dot import write dotdata = write(graph) from pydot import graph_from_dot_data dotgraph = graph_from_dot_data(dotdata) dotgraph.write(filename, format=format) def write_tag_graph(self, root, filename, format='png'): graph = self.build_tag_graph(root) self.write_graph(graph, filename, format=format) # TODO: refactor this as a class. # TODO: make the dump command's `path` option a general one. def cli(args, in_, out, err, Dumper=Dumper): """Provide a command-line interface to the module functionality. Dumper: xmlearn.Dumper or subclass. Called in response to the `dump` subcommand. Note that this should be the *class*, not an instantiation of it. args: the arguments to be parsed. in_, out, err: open input/output/error files. """ from argparse import ArgumentParser, FileType def call_function(ns): """Calls `ns.function`, passing arguments as determined by `ns`. Attributes of `ns` which are listed in `ns.kw_from_ns` are added to the set of keyword arguments passed to `ns.function`. """ kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if key in ns.kw_from_ns) return ns.function(**kwargs) def dump(ns): """Initializes a Dumper with values from the namespace `ns`. False values are filtered out. Calls its `dump` method, sending output to `out`. """ if ns.list is False: kw_from_ns = ['width', 'maxdepth', 'ruleset'] kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if value) kwargs['outstream'] = out dumper = Dumper(**kwargs) from lxml.etree import parse, XPath root = parse(ns.infile).getroot() if ns.path: path = XPath(ns.path) return [dumper.dump(e) for e in path(root)] else: return dumper.dump(root) else: return Dumper.print_rulesets(ruleset=ns.list, verbose=ns.verbose) - # Map subcommands to actions. - # This seemed necessary because it's not possible to - # use set_defaults to control nested subcommands. - # Then I discovered that you can't implement optional subcommands. - # At this point it could be worked back into set_defaults calls, - # but it may be useful to use nested subcommands at a later point. - action_map = {} - parser = ArgumentParser() parser.add_argument('-i', '--infile', type=FileType, default=in_, help='The XML file to learn about.\n' 'Defaults to stdin.') - subparsers = parser.add_subparsers(title='subcommands', dest='action') + subparsers = parser.add_subparsers(title='subcommands') p_dump = subparsers.add_parser('dump', help='Dump xml data according to a set of rules.', description='Dump xml data according to a set of rules.') - action_map['dump'] = {'action': dump} - + p_dump.set_defaults(action=dump) # TODO: rework argparsing (again) to use custom Actions. p_dump.add_argument('-l', '--list-rulesets', metavar='RULESET', nargs='?', default=False, dest='list', help='Get a list of rulesets ' 'or information about a particular ruleset') # TODO: make the required nature of -r depend on the presence of a ruleset p_dump.add_argument('-r', '--ruleset', choices=Dumper.rulesets.keys(), default=Dumper.default_ruleset, help='Which set of rules to apply.\nDefaults to "{0}".' .format(Dumper.default_ruleset)) p_dump.add_argument('-d', '--maxdepth', type=int, help='How many levels to dump.') # TODO: set default width to console width p_dump.add_argument('-w', '--width', type=int, help='The output width of the dump.') p_dump.add_argument('-v', '--verbose', action='store_true', help='Enable verbose ruleset list.\n' 'Only useful with `-l`.') p_dump.add_argument(dest='path', nargs='?', default=None, help='The XPath to the node to be dumped.\n' 'Defaults to the root node.') namespace = parser.parse_args(args) - # Push the action map into the namespace - for attrib, value in action_map[namespace.action].iteritems(): - setattr(namespace, attrib, value) - return namespace.action(namespace) if __name__ == '__main__': from sys import argv, stdin, stdout, stderr cli(argv[1:], stdin, stdout, stderr)
intuited/xmlearn
8ebf35c2f62bc4642d8c569cac0ae37bb2b48103
cleanup documentation
diff --git a/__init__.py b/__init__.py index 32db67c..a4bfc0a 100755 --- a/__init__.py +++ b/__init__.py @@ -1,305 +1,306 @@ #!/usr/bin/env python """Library and CLI for learning about XML formats.""" from lxml import etree class Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. ruleset: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. outstream: a stream to which the dump will be written. For now, this function is just useful for sussing out the shape of the XML. """ # TODO: write doctest examples # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'full': {None: {'recurse': True}}} default_ruleset = 'full' from sys import stdout outstream = stdout from pprint import PrettyPrinter pformat = PrettyPrinter(indent=2).pformat # Some more defaults. maxdepth = None width = 80 # This should maybe be moved into the CLI. @classmethod def print_rulesets(cls, ruleset=None, outstream=None, format=pformat, verbose=False): """Output ruleset information. If a `ruleset` is given, that ruleset's rules are output. If no `ruleset` is given, a list of rulesets is output. The `verbose` option will cause full ruleset information to be given in the list of rulesets. `format` can be used to specify a different formatting function. """ outstream = outstream if outstream else cls.outstream if ruleset: outstream.write(format(cls.rulesets[ruleset])) else: if verbose: outstream.write(format(cls.rulesets)) else: outstream.writelines("\n".join(cls.rulesets.keys())) outstream.write("\n") def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `ruleset`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `outstream`, `maxdepth`, and `ruleset` object attributes can be overridden without modifying the object. If `ruleset` is not given, `self`'s default ruleset is used. I suspect that actually using XSLT would be a better way to do this. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) # Pull variables from kwargs or self maxdepth, outstream = (kwargs.pop(v, getattr(self, v)) for v in ('maxdepth', 'outstream')) ruleset = kwargs.pop('ruleset', getattr(self, 'ruleset', self.default_ruleset)) if isinstance(ruleset, basestring): ruleset = self.rulesets[ruleset] assert isinstance(ruleset, Mapping) def _dump(element, depth=0): for rule in ruleset.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) outstream.write(self.format_element(element, depth, **kwargs)) outstream.write("\n") if recurse: if (maxdepth is None or maxdepth > depth): for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) def iter_unique_child_tags(self, root, tag): """Iterates through unique child tags for all instances of `tag`. Iteration starts at `root`. """ found_child_tags = set() instances = root.iterdescendants(tag) from itertools import chain child_nodes = chain.from_iterable(i.getchildren() for i in instances) child_tags = (n.tag for n in child_nodes) for t in child_tags: if t not in found_child_tags: found_child_tags.add(t) yield t def iter_tag_list(self, root): """List all unique tags at and under the `root` node.""" found_tags = set() tags = (n.tag for n in root.iterdescendants() if hasattr(n, 'tag')) for t in tags: if t not in found_tags: found_tags.add(t) yield t def build_tag_graph(self, root): """Build a python-graph graph of the tag relationships.""" from pygraph.classes.digraph import digraph g = digraph() tags = list(self.iter_tag_list(root)) g.add_nodes(tags) for parent in tags: for child in self.iter_unique_child_tags(root, parent): g.add_edge((parent, child)) return g def write_graph(self, graph, filename, format='png'): """Write a python-graph graph as an image. `format` can be any of those supported by pydot.Dot.write(). """ from pygraph.readwrite.dot import write dotdata = write(graph) from pydot import graph_from_dot_data dotgraph = graph_from_dot_data(dotdata) dotgraph.write(filename, format=format) def write_tag_graph(self, root, filename, format='png'): graph = self.build_tag_graph(root) self.write_graph(graph, filename, format=format) # TODO: refactor this as a class. # TODO: make the dump command's `path` option a general one. def cli(args, in_, out, err, Dumper=Dumper): """Provide a command-line interface to the module functionality. - Dumper: an xmlearn.Dumper or subclass. + Dumper: xmlearn.Dumper or subclass. Called in response to the `dump` subcommand. + Note that this should be the *class*, not an instantiation of it. args: the arguments to be parsed. in_, out, err: open input/output/error files. """ from argparse import ArgumentParser, FileType def call_function(ns): """Calls `ns.function`, passing arguments as determined by `ns`. Attributes of `ns` which are listed in `ns.kw_from_ns` are added to the set of keyword arguments passed to `ns.function`. """ kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if key in ns.kw_from_ns) return ns.function(**kwargs) def dump(ns): """Initializes a Dumper with values from the namespace `ns`. False values are filtered out. Calls its `dump` method, sending output to `out`. """ if ns.list is False: kw_from_ns = ['width', 'maxdepth', 'ruleset'] kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if value) kwargs['outstream'] = out dumper = Dumper(**kwargs) from lxml.etree import parse, XPath root = parse(ns.infile).getroot() if ns.path: path = XPath(ns.path) return [dumper.dump(e) for e in path(root)] else: return dumper.dump(root) else: return Dumper.print_rulesets(ruleset=ns.list, verbose=ns.verbose) # Map subcommands to actions. # This seemed necessary because it's not possible to # use set_defaults to control nested subcommands. # Then I discovered that you can't implement optional subcommands. # At this point it could be worked back into set_defaults calls, # but it may be useful to use nested subcommands at a later point. action_map = {} parser = ArgumentParser() parser.add_argument('-i', '--infile', type=FileType, default=in_, help='The XML file to learn about.\n' 'Defaults to stdin.') subparsers = parser.add_subparsers(title='subcommands', dest='action') p_dump = subparsers.add_parser('dump', help='Dump xml data according to a set of rules.', description='Dump xml data according to a set of rules.') action_map['dump'] = {'action': dump} # TODO: rework argparsing (again) to use custom Actions. p_dump.add_argument('-l', '--list-rulesets', metavar='RULESET', nargs='?', default=False, dest='list', help='Get a list of rulesets ' 'or information about a particular ruleset') # TODO: make the required nature of -r depend on the presence of a ruleset p_dump.add_argument('-r', '--ruleset', choices=Dumper.rulesets.keys(), default=Dumper.default_ruleset, help='Which set of rules to apply.\nDefaults to "{0}".' .format(Dumper.default_ruleset)) p_dump.add_argument('-d', '--maxdepth', type=int, help='How many levels to dump.') # TODO: set default width to console width p_dump.add_argument('-w', '--width', type=int, help='The output width of the dump.') p_dump.add_argument('-v', '--verbose', action='store_true', help='Enable verbose ruleset list.\n' 'Only useful with `-l`.') p_dump.add_argument(dest='path', nargs='?', default=None, help='The XPath to the node to be dumped.\n' 'Defaults to the root node.') namespace = parser.parse_args(args) # Push the action map into the namespace for attrib, value in action_map[namespace.action].iteritems(): setattr(namespace, attrib, value) return namespace.action(namespace) if __name__ == '__main__': from sys import argv, stdin, stdout, stderr cli(argv[1:], stdin, stdout, stderr)
intuited/xmlearn
d239625cd9e091d984979f39a62578fe903158c0
cleanup debugging code and remnants of a failed venture
diff --git a/__init__.py b/__init__.py index dfdd788..32db67c 100755 --- a/__init__.py +++ b/__init__.py @@ -1,319 +1,305 @@ #!/usr/bin/env python """Library and CLI for learning about XML formats.""" -from deboogie import get_debug_logger -debug = get_debug_logger('xmlearn') - from lxml import etree class Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. ruleset: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. outstream: a stream to which the dump will be written. For now, this function is just useful for sussing out the shape of the XML. """ # TODO: write doctest examples # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'full': {None: {'recurse': True}}} default_ruleset = 'full' from sys import stdout outstream = stdout from pprint import PrettyPrinter pformat = PrettyPrinter(indent=2).pformat # Some more defaults. maxdepth = None width = 80 # This should maybe be moved into the CLI. @classmethod def print_rulesets(cls, ruleset=None, outstream=None, format=pformat, verbose=False): """Output ruleset information. If a `ruleset` is given, that ruleset's rules are output. If no `ruleset` is given, a list of rulesets is output. The `verbose` option will cause full ruleset information to be given in the list of rulesets. `format` can be used to specify a different formatting function. """ outstream = outstream if outstream else cls.outstream if ruleset: outstream.write(format(cls.rulesets[ruleset])) else: if verbose: outstream.write(format(cls.rulesets)) else: outstream.writelines("\n".join(cls.rulesets.keys())) outstream.write("\n") def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `ruleset`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `outstream`, `maxdepth`, and `ruleset` object attributes can be overridden without modifying the object. If `ruleset` is not given, `self`'s default ruleset is used. I suspect that actually using XSLT would be a better way to do this. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) # Pull variables from kwargs or self maxdepth, outstream = (kwargs.pop(v, getattr(self, v)) for v in ('maxdepth', 'outstream')) ruleset = kwargs.pop('ruleset', getattr(self, 'ruleset', self.default_ruleset)) if isinstance(ruleset, basestring): ruleset = self.rulesets[ruleset] assert isinstance(ruleset, Mapping) def _dump(element, depth=0): for rule in ruleset.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) outstream.write(self.format_element(element, depth, **kwargs)) outstream.write("\n") if recurse: if (maxdepth is None or maxdepth > depth): for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) def iter_unique_child_tags(self, root, tag): """Iterates through unique child tags for all instances of `tag`. Iteration starts at `root`. """ found_child_tags = set() instances = root.iterdescendants(tag) from itertools import chain child_nodes = chain.from_iterable(i.getchildren() for i in instances) child_tags = (n.tag for n in child_nodes) for t in child_tags: if t not in found_child_tags: found_child_tags.add(t) yield t def iter_tag_list(self, root): """List all unique tags at and under the `root` node.""" found_tags = set() tags = (n.tag for n in root.iterdescendants() if hasattr(n, 'tag')) for t in tags: if t not in found_tags: found_tags.add(t) yield t def build_tag_graph(self, root): """Build a python-graph graph of the tag relationships.""" from pygraph.classes.digraph import digraph g = digraph() tags = list(self.iter_tag_list(root)) g.add_nodes(tags) for parent in tags: for child in self.iter_unique_child_tags(root, parent): g.add_edge((parent, child)) return g def write_graph(self, graph, filename, format='png'): """Write a python-graph graph as an image. `format` can be any of those supported by pydot.Dot.write(). """ from pygraph.readwrite.dot import write dotdata = write(graph) from pydot import graph_from_dot_data dotgraph = graph_from_dot_data(dotdata) dotgraph.write(filename, format=format) def write_tag_graph(self, root, filename, format='png'): graph = self.build_tag_graph(root) self.write_graph(graph, filename, format=format) # TODO: refactor this as a class. # TODO: make the dump command's `path` option a general one. def cli(args, in_, out, err, Dumper=Dumper): """Provide a command-line interface to the module functionality. Dumper: an xmlearn.Dumper or subclass. Called in response to the `dump` subcommand. args: the arguments to be parsed. in_, out, err: open input/output/error files. """ from argparse import ArgumentParser, FileType def call_function(ns): """Calls `ns.function`, passing arguments as determined by `ns`. Attributes of `ns` which are listed in `ns.kw_from_ns` are added to the set of keyword arguments passed to `ns.function`. """ kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if key in ns.kw_from_ns) return ns.function(**kwargs) def dump(ns): """Initializes a Dumper with values from the namespace `ns`. False values are filtered out. Calls its `dump` method, sending output to `out`. """ if ns.list is False: kw_from_ns = ['width', 'maxdepth', 'ruleset'] kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if value) kwargs['outstream'] = out dumper = Dumper(**kwargs) from lxml.etree import parse, XPath root = parse(ns.infile).getroot() if ns.path: path = XPath(ns.path) return [dumper.dump(e) for e in path(root)] else: return dumper.dump(root) else: return Dumper.print_rulesets(ruleset=ns.list, verbose=ns.verbose) # Map subcommands to actions. # This seemed necessary because it's not possible to # use set_defaults to control nested subcommands. # Then I discovered that you can't implement optional subcommands. # At this point it could be worked back into set_defaults calls, # but it may be useful to use nested subcommands at a later point. action_map = {} parser = ArgumentParser() parser.add_argument('-i', '--infile', type=FileType, default=in_, help='The XML file to learn about.\n' 'Defaults to stdin.') subparsers = parser.add_subparsers(title='subcommands', dest='action') p_dump = subparsers.add_parser('dump', help='Dump xml data according to a set of rules.', description='Dump xml data according to a set of rules.') action_map['dump'] = {'action': dump} # TODO: rework argparsing (again) to use custom Actions. -##--Doesn't work because it forces the use of a subcommand. -##-- p_dump_subp = p_dump.add_subparsers(title='subcommands', dest='action') -##-- p_dump_rules = p_dump_subp.add_parser('rules', -##-- help='Get information about available rules', -##-- description=Dumper.print_rulesets.__doc__) -##-- action_map['rules'] = {'action': call_function, -##-- 'function': Dumper.print_rulesets, -##-- 'kw_from_ns': ['verbose', 'ruleset']} -##-- p_dump_rules.add_argument('-v', '--verbose', action='store_true') -##-- p_dump_rules.add_argument(dest='ruleset', nargs='?', -##-- choices=Dumper.rulesets) p_dump.add_argument('-l', '--list-rulesets', metavar='RULESET', nargs='?', default=False, dest='list', help='Get a list of rulesets ' 'or information about a particular ruleset') # TODO: make the required nature of -r depend on the presence of a ruleset p_dump.add_argument('-r', '--ruleset', choices=Dumper.rulesets.keys(), default=Dumper.default_ruleset, help='Which set of rules to apply.\nDefaults to "{0}".' .format(Dumper.default_ruleset)) p_dump.add_argument('-d', '--maxdepth', type=int, help='How many levels to dump.') # TODO: set default width to console width p_dump.add_argument('-w', '--width', type=int, help='The output width of the dump.') p_dump.add_argument('-v', '--verbose', action='store_true', help='Enable verbose ruleset list.\n' 'Only useful with `-l`.') p_dump.add_argument(dest='path', nargs='?', default=None, help='The XPath to the node to be dumped.\n' 'Defaults to the root node.') namespace = parser.parse_args(args) # Push the action map into the namespace for attrib, value in action_map[namespace.action].iteritems(): setattr(namespace, attrib, value) return namespace.action(namespace) if __name__ == '__main__': from sys import argv, stdin, stdout, stderr cli(argv[1:], stdin, stdout, stderr)
intuited/xmlearn
85b76fd3049bba420a6147f94ebef723596c6848
refactor to target general-purpose XML files.
diff --git a/README b/README index f72f23c..a3cdbc0 100644 --- a/README +++ b/README @@ -1 +1 @@ -Library for parsing MPD's XML documentation. +Library and CLI for learning about XML formats. diff --git a/__init__.py b/__init__.py index bb97182..dfdd788 100755 --- a/__init__.py +++ b/__init__.py @@ -1,327 +1,319 @@ #!/usr/bin/env python -"""Routines to parse mpd's protocol documentation.""" -# TODO: refactor almost the entirety of this code into -# a general-purpose library not targeted at MPD. +"""Library and CLI for learning about XML formats.""" -# TODO: rename this class `Dumper`. -class LXML_Dumper(object): +from deboogie import get_debug_logger +debug = get_debug_logger('xmlearn') + +from lxml import etree + +class Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. ruleset: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. + outstream: a stream to which the dump will be written. For now, this function is just useful for sussing out the shape of the XML. - - Setup: - >>> import lxml.etree as etree - >>> book = etree.parse('protocol.xml').getroot() - >>> dumper = LXML_Dumper(maxdepth=2) - >>> dumper.dump(book) - The Music Player Daemon protocol (/book): - [title] (/book/title): The Music Player Daemon protocol - General protocol syntax (/book/chapter[1]): - [title] (/book/chapter[1]/title): General protocol syntax - Requests (/book/chapter[1]/section[1]) - Responses (/book/chapter[1]/section[2]) - Command lists (/book/chapter[1]/section[3]) - Ranges (/book/chapter[1]/section[4]) - Command reference (/book/chapter[2]): - [title] (/book/chapter[2]/title): Command reference - [note] (/book/chapter[2]/note): - Querying MPD's status (/book/chapter[2]/section[1]) - Playback options (/book/chapter[2]/section[2]) - Controlling playback (/book/chapter[2]/section[3]) - The current playlist (/book/chapter[2]/section[4]) - Stored playlists (/book/chapter[2]/section[5]) - The music database (/book/chapter[2]/section[6]) - Stickers (/book/chapter[2]/section[7]) - Connection settings (/book/chapter[2]/section[8]) - Audio output devices (/book/chapter[2]/section[9]) - Reflection (/book/chapter[2]/section[10]) - >>> for c in book.iterdescendants('section'): - ... dumper.dump(c, maxdepth=0, ruleset='full') - Requests (/book/chapter[1]/section[1]): - Responses (/book/chapter[1]/section[2]): - Command lists (/book/chapter[1]/section[3]): - Ranges (/book/chapter[1]/section[4]): - Querying MPD's status (/book/chapter[2]/section[1]): - Playback options (/book/chapter[2]/section[2]): - Controlling playback (/book/chapter[2]/section[3]): - The current playlist (/book/chapter[2]/section[4]): - Stored playlists (/book/chapter[2]/section[5]): - The music database (/book/chapter[2]/section[6]): - Stickers (/book/chapter[2]/section[7]): - Connection settings (/book/chapter[2]/section[8]): - Audio output devices (/book/chapter[2]/section[9]): - Reflection (/book/chapter[2]/section[10]): - """ + # TODO: write doctest examples # Each ruleset maps tags to kwargs for `format_element`. - rulesets = {'book': {'section': {'with_text': False}, - 'para': {'linebreak': True}, - None: {'recurse': True}}, - 'full': {None: {'recurse': True}}} - default_ruleset = 'book' + rulesets = {'full': {None: {'recurse': True}}} + + default_ruleset = 'full' + from sys import stdout + outstream = stdout + from pprint import PrettyPrinter pformat = PrettyPrinter(indent=2).pformat + + # Some more defaults. + maxdepth = None + width = 80 + + # This should maybe be moved into the CLI. @classmethod - def print_rulesets(cls, ruleset=None, outstream=stdout, + def print_rulesets(cls, ruleset=None, outstream=None, format=pformat, verbose=False): """Output ruleset information. If a `ruleset` is given, that ruleset's rules are output. If no `ruleset` is given, a list of rulesets is output. The `verbose` option will cause full ruleset information to be given in the list of rulesets. `format` can be used to specify a different formatting function. """ + outstream = outstream if outstream else cls.outstream + if ruleset: outstream.write(format(cls.rulesets[ruleset])) else: if verbose: outstream.write(format(cls.rulesets)) else: outstream.writelines("\n".join(cls.rulesets.keys())) outstream.write("\n") - maxdepth = None - width = 80 - ruleset = rulesets['book'] def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) - # TODO: this function should take an output stream. def dump(self, element, **kwargs): """Dump `element` according to `ruleset`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. - Additionally, the `maxdepth` and `ruleset` object keyword arguments - can be overridden. + Additionally, the `outstream`, `maxdepth`, and `ruleset` + object attributes can be overridden without modifying the object. + + If `ruleset` is not given, `self`'s default ruleset is used. + + I suspect that actually using XSLT would be a better way to do this. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) - maxdepth, ruleset = (kwargs.pop(a, getattr(self, a)) - for a in ('maxdepth', 'ruleset')) + # Pull variables from kwargs or self + maxdepth, outstream = (kwargs.pop(v, getattr(self, v)) + for v in ('maxdepth', 'outstream')) - if isinstance(ruleset, Mapping): - pass - elif isinstance(ruleset, basestring): + ruleset = kwargs.pop('ruleset', getattr(self, 'ruleset', + self.default_ruleset)) + + if isinstance(ruleset, basestring): ruleset = self.rulesets[ruleset] assert isinstance(ruleset, Mapping) def _dump(element, depth=0): for rule in ruleset.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) - print self.format_element(element, depth, **kwargs) + outstream.write(self.format_element(element, depth, **kwargs)) + outstream.write("\n") if recurse: if (maxdepth is None or maxdepth > depth): for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) def iter_unique_child_tags(self, root, tag): """Iterates through unique child tags for all instances of `tag`. Iteration starts at `root`. """ found_child_tags = set() instances = root.iterdescendants(tag) from itertools import chain child_nodes = chain.from_iterable(i.getchildren() for i in instances) child_tags = (n.tag for n in child_nodes) for t in child_tags: if t not in found_child_tags: found_child_tags.add(t) yield t def iter_tag_list(self, root): """List all unique tags at and under the `root` node.""" found_tags = set() tags = (n.tag for n in root.iterdescendants() if hasattr(n, 'tag')) for t in tags: if t not in found_tags: found_tags.add(t) yield t def build_tag_graph(self, root): """Build a python-graph graph of the tag relationships.""" from pygraph.classes.digraph import digraph g = digraph() tags = list(self.iter_tag_list(root)) g.add_nodes(tags) for parent in tags: for child in self.iter_unique_child_tags(root, parent): g.add_edge((parent, child)) return g def write_graph(self, graph, filename, format='png'): """Write a python-graph graph as an image. `format` can be any of those supported by pydot.Dot.write(). """ from pygraph.readwrite.dot import write dotdata = write(graph) from pydot import graph_from_dot_data dotgraph = graph_from_dot_data(dotdata) dotgraph.write(filename, format=format) def write_tag_graph(self, root, filename, format='png'): graph = self.build_tag_graph(root) self.write_graph(graph, filename, format=format) -def cli(args, in_, out, err): +# TODO: refactor this as a class. +# TODO: make the dump command's `path` option a general one. +def cli(args, in_, out, err, Dumper=Dumper): + """Provide a command-line interface to the module functionality. + + Dumper: an xmlearn.Dumper or subclass. + Called in response to the `dump` subcommand. + + args: the arguments to be parsed. + + in_, out, err: open input/output/error files. + """ + from argparse import ArgumentParser, FileType def call_function(ns): """Calls `ns.function`, passing arguments as determined by `ns`. Attributes of `ns` which are listed in `ns.kw_from_ns` are added to the set of keyword arguments passed to `ns.function`. """ kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if key in ns.kw_from_ns) return ns.function(**kwargs) def dump(ns): + """Initializes a Dumper with values from the namespace `ns`. + + False values are filtered out. + + Calls its `dump` method, sending output to `out`. + """ if ns.list is False: kw_from_ns = ['width', 'maxdepth', 'ruleset'] kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() if value) - dumper = LXML_Dumper(**kwargs) + kwargs['outstream'] = out + dumper = Dumper(**kwargs) from lxml.etree import parse, XPath root = parse(ns.infile).getroot() if ns.path: path = XPath(ns.path) return [dumper.dump(e) for e in path(root)] else: return dumper.dump(root) else: - return LXML_Dumper.print_rulesets(ruleset=ns.list, + return Dumper.print_rulesets(ruleset=ns.list, verbose=ns.verbose) # Map subcommands to actions. # This seemed necessary because it's not possible to # use set_defaults to control nested subcommands. # Then I discovered that you can't implement optional subcommands. # At this point it could be worked back into set_defaults calls, # but it may be useful to use nested subcommands at a later point. action_map = {} parser = ArgumentParser() parser.add_argument('-i', '--infile', type=FileType, default=in_, help='The XML file to learn about.\n' 'Defaults to stdin.') subparsers = parser.add_subparsers(title='subcommands', dest='action') p_dump = subparsers.add_parser('dump', help='Dump xml data according to a set of rules.', description='Dump xml data according to a set of rules.') action_map['dump'] = {'action': dump} + # TODO: rework argparsing (again) to use custom Actions. ##--Doesn't work because it forces the use of a subcommand. ##-- p_dump_subp = p_dump.add_subparsers(title='subcommands', dest='action') ##-- p_dump_rules = p_dump_subp.add_parser('rules', ##-- help='Get information about available rules', -##-- description=LXML_Dumper.print_rulesets.__doc__) +##-- description=Dumper.print_rulesets.__doc__) ##-- action_map['rules'] = {'action': call_function, -##-- 'function': LXML_Dumper.print_rulesets, +##-- 'function': Dumper.print_rulesets, ##-- 'kw_from_ns': ['verbose', 'ruleset']} ##-- p_dump_rules.add_argument('-v', '--verbose', action='store_true') ##-- p_dump_rules.add_argument(dest='ruleset', nargs='?', -##-- choices=LXML_Dumper.rulesets) +##-- choices=Dumper.rulesets) p_dump.add_argument('-l', '--list-rulesets', metavar='RULESET', nargs='?', default=False, dest='list', help='Get a list of rulesets ' 'or information about a particular ruleset') # TODO: make the required nature of -r depend on the presence of a ruleset p_dump.add_argument('-r', '--ruleset', - choices=LXML_Dumper.rulesets.keys(), - default=LXML_Dumper.default_ruleset, + choices=Dumper.rulesets.keys(), + default=Dumper.default_ruleset, help='Which set of rules to apply.\nDefaults to "{0}".' - .format(LXML_Dumper.default_ruleset)) + .format(Dumper.default_ruleset)) p_dump.add_argument('-d', '--maxdepth', type=int, help='How many levels to dump.') # TODO: set default width to console width p_dump.add_argument('-w', '--width', type=int, help='The output width of the dump.') p_dump.add_argument('-v', '--verbose', action='store_true', help='Enable verbose ruleset list.\n' 'Only useful with `-l`.') p_dump.add_argument(dest='path', nargs='?', default=None, help='The XPath to the node to be dumped.\n' 'Defaults to the root node.') namespace = parser.parse_args(args) # Push the action map into the namespace for attrib, value in action_map[namespace.action].iteritems(): setattr(namespace, attrib, value) return namespace.action(namespace) if __name__ == '__main__': from sys import argv, stdin, stdout, stderr cli(argv[1:], stdin, stdout, stderr) diff --git a/xmlearn b/xmlearn new file mode 120000 index 0000000..93f5256 --- /dev/null +++ b/xmlearn @@ -0,0 +1 @@ +__init__.py \ No newline at end of file
intuited/xmlearn
c96d932614c1aa95eca015513fe6188b7611ed72
add CLI capable of doing dumps.
diff --git a/__init__.py b/__init__.py old mode 100644 new mode 100755 index 51cfbf8..bb97182 --- a/__init__.py +++ b/__init__.py @@ -1,198 +1,327 @@ +#!/usr/bin/env python """Routines to parse mpd's protocol documentation.""" +# TODO: refactor almost the entirety of this code into +# a general-purpose library not targeted at MPD. +# TODO: rename this class `Dumper`. class LXML_Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. - rules: either a string matching one of the keys of rulesets, + ruleset: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. For now, this function is just useful for sussing out the shape of the XML. Setup: >>> import lxml.etree as etree >>> book = etree.parse('protocol.xml').getroot() >>> dumper = LXML_Dumper(maxdepth=2) >>> dumper.dump(book) The Music Player Daemon protocol (/book): [title] (/book/title): The Music Player Daemon protocol General protocol syntax (/book/chapter[1]): [title] (/book/chapter[1]/title): General protocol syntax Requests (/book/chapter[1]/section[1]) Responses (/book/chapter[1]/section[2]) Command lists (/book/chapter[1]/section[3]) Ranges (/book/chapter[1]/section[4]) Command reference (/book/chapter[2]): [title] (/book/chapter[2]/title): Command reference [note] (/book/chapter[2]/note): Querying MPD's status (/book/chapter[2]/section[1]) Playback options (/book/chapter[2]/section[2]) Controlling playback (/book/chapter[2]/section[3]) The current playlist (/book/chapter[2]/section[4]) Stored playlists (/book/chapter[2]/section[5]) The music database (/book/chapter[2]/section[6]) Stickers (/book/chapter[2]/section[7]) Connection settings (/book/chapter[2]/section[8]) Audio output devices (/book/chapter[2]/section[9]) Reflection (/book/chapter[2]/section[10]) >>> for c in book.iterdescendants('section'): - ... dumper.dump(c, maxdepth=0, rules='full') + ... dumper.dump(c, maxdepth=0, ruleset='full') Requests (/book/chapter[1]/section[1]): Responses (/book/chapter[1]/section[2]): Command lists (/book/chapter[1]/section[3]): Ranges (/book/chapter[1]/section[4]): Querying MPD's status (/book/chapter[2]/section[1]): Playback options (/book/chapter[2]/section[2]): Controlling playback (/book/chapter[2]/section[3]): The current playlist (/book/chapter[2]/section[4]): Stored playlists (/book/chapter[2]/section[5]): The music database (/book/chapter[2]/section[6]): Stickers (/book/chapter[2]/section[7]): Connection settings (/book/chapter[2]/section[8]): Audio output devices (/book/chapter[2]/section[9]): Reflection (/book/chapter[2]/section[10]): """ # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'book': {'section': {'with_text': False}, 'para': {'linebreak': True}, None: {'recurse': True}}, 'full': {None: {'recurse': True}}} + default_ruleset = 'book' + from sys import stdout + from pprint import PrettyPrinter + pformat = PrettyPrinter(indent=2).pformat + @classmethod + def print_rulesets(cls, ruleset=None, outstream=stdout, + format=pformat, verbose=False): + """Output ruleset information. + + If a `ruleset` is given, that ruleset's rules are output. + If no `ruleset` is given, a list of rulesets is output. + + The `verbose` option will cause full ruleset information + to be given in the list of rulesets. + + `format` can be used to specify a different formatting function. + """ + + if ruleset: + outstream.write(format(cls.rulesets[ruleset])) + else: + if verbose: + outstream.write(format(cls.rulesets)) + else: + outstream.writelines("\n".join(cls.rulesets.keys())) + outstream.write("\n") maxdepth = None width = 80 - rules = rulesets['book'] + ruleset = rulesets['book'] def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) + # TODO: this function should take an output stream. def dump(self, element, **kwargs): - """Dump `element` according to `rules`. + """Dump `element` according to `ruleset`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. - Additionally, the `maxdepth` and `rules` object keyword arguments + Additionally, the `maxdepth` and `ruleset` object keyword arguments can be overridden. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) - maxdepth, rules = (kwargs.pop(a, getattr(self, a)) - for a in ('maxdepth', 'rules')) + maxdepth, ruleset = (kwargs.pop(a, getattr(self, a)) + for a in ('maxdepth', 'ruleset')) - if isinstance(rules, Mapping): + if isinstance(ruleset, Mapping): pass - elif isinstance(rules, basestring): - rules = self.rulesets[rules] - assert isinstance(rules, Mapping) + elif isinstance(ruleset, basestring): + ruleset = self.rulesets[ruleset] + assert isinstance(ruleset, Mapping) def _dump(element, depth=0): - for rule in rules.iteritems(): + for rule in ruleset.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) print self.format_element(element, depth, **kwargs) if recurse: if (maxdepth is None or maxdepth > depth): for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) - + def iter_unique_child_tags(self, root, tag): """Iterates through unique child tags for all instances of `tag`. Iteration starts at `root`. """ found_child_tags = set() instances = root.iterdescendants(tag) from itertools import chain child_nodes = chain.from_iterable(i.getchildren() for i in instances) child_tags = (n.tag for n in child_nodes) for t in child_tags: if t not in found_child_tags: found_child_tags.add(t) yield t def iter_tag_list(self, root): """List all unique tags at and under the `root` node.""" found_tags = set() tags = (n.tag for n in root.iterdescendants() if hasattr(n, 'tag')) for t in tags: if t not in found_tags: found_tags.add(t) yield t def build_tag_graph(self, root): """Build a python-graph graph of the tag relationships.""" from pygraph.classes.digraph import digraph g = digraph() tags = list(self.iter_tag_list(root)) g.add_nodes(tags) for parent in tags: for child in self.iter_unique_child_tags(root, parent): g.add_edge((parent, child)) return g def write_graph(self, graph, filename, format='png'): """Write a python-graph graph as an image. `format` can be any of those supported by pydot.Dot.write(). """ from pygraph.readwrite.dot import write dotdata = write(graph) from pydot import graph_from_dot_data dotgraph = graph_from_dot_data(dotdata) dotgraph.write(filename, format=format) def write_tag_graph(self, root, filename, format='png'): graph = self.build_tag_graph(root) self.write_graph(graph, filename, format=format) + + +def cli(args, in_, out, err): + from argparse import ArgumentParser, FileType + + def call_function(ns): + """Calls `ns.function`, passing arguments as determined by `ns`. + + Attributes of `ns` which are listed in `ns.kw_from_ns` + are added to the set of keyword arguments passed to `ns.function`. + """ + kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() + if key in ns.kw_from_ns) + return ns.function(**kwargs) + + def dump(ns): + if ns.list is False: + kw_from_ns = ['width', 'maxdepth', 'ruleset'] + kwargs = dict((key, value) for key, value in ns.__dict__.iteritems() + if value) + dumper = LXML_Dumper(**kwargs) + from lxml.etree import parse, XPath + root = parse(ns.infile).getroot() + if ns.path: + path = XPath(ns.path) + return [dumper.dump(e) for e in path(root)] + else: + return dumper.dump(root) + else: + return LXML_Dumper.print_rulesets(ruleset=ns.list, + verbose=ns.verbose) + + # Map subcommands to actions. + # This seemed necessary because it's not possible to + # use set_defaults to control nested subcommands. + # Then I discovered that you can't implement optional subcommands. + # At this point it could be worked back into set_defaults calls, + # but it may be useful to use nested subcommands at a later point. + action_map = {} + + parser = ArgumentParser() + parser.add_argument('-i', '--infile', type=FileType, default=in_, + help='The XML file to learn about.\n' + 'Defaults to stdin.') + + subparsers = parser.add_subparsers(title='subcommands', dest='action') + p_dump = subparsers.add_parser('dump', + help='Dump xml data according to a set of rules.', + description='Dump xml data according to a set of rules.') + action_map['dump'] = {'action': dump} + +##--Doesn't work because it forces the use of a subcommand. +##-- p_dump_subp = p_dump.add_subparsers(title='subcommands', dest='action') +##-- p_dump_rules = p_dump_subp.add_parser('rules', +##-- help='Get information about available rules', +##-- description=LXML_Dumper.print_rulesets.__doc__) +##-- action_map['rules'] = {'action': call_function, +##-- 'function': LXML_Dumper.print_rulesets, +##-- 'kw_from_ns': ['verbose', 'ruleset']} +##-- p_dump_rules.add_argument('-v', '--verbose', action='store_true') +##-- p_dump_rules.add_argument(dest='ruleset', nargs='?', +##-- choices=LXML_Dumper.rulesets) + + p_dump.add_argument('-l', '--list-rulesets', metavar='RULESET', + nargs='?', default=False, dest='list', + help='Get a list of rulesets ' + 'or information about a particular ruleset') + # TODO: make the required nature of -r depend on the presence of a ruleset + p_dump.add_argument('-r', '--ruleset', + choices=LXML_Dumper.rulesets.keys(), + default=LXML_Dumper.default_ruleset, + help='Which set of rules to apply.\nDefaults to "{0}".' + .format(LXML_Dumper.default_ruleset)) + p_dump.add_argument('-d', '--maxdepth', type=int, + help='How many levels to dump.') + # TODO: set default width to console width + p_dump.add_argument('-w', '--width', type=int, + help='The output width of the dump.') + p_dump.add_argument('-v', '--verbose', action='store_true', + help='Enable verbose ruleset list.\n' + 'Only useful with `-l`.') + + p_dump.add_argument(dest='path', nargs='?', default=None, + help='The XPath to the node to be dumped.\n' + 'Defaults to the root node.') + + namespace = parser.parse_args(args) + + # Push the action map into the namespace + for attrib, value in action_map[namespace.action].iteritems(): + setattr(namespace, attrib, value) + + return namespace.action(namespace) + + +if __name__ == '__main__': + from sys import argv, stdin, stdout, stderr + cli(argv[1:], stdin, stdout, stderr)
intuited/xmlearn
1e4cfa559708d8a723228bbaa1af2c7b808ae5a8
add graph capabilities, integrating with python-graph and pydot
diff --git a/__init__.py b/__init__.py index 607e5f1..51cfbf8 100644 --- a/__init__.py +++ b/__init__.py @@ -1,167 +1,198 @@ """Routines to parse mpd's protocol documentation.""" class LXML_Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. rules: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. For now, this function is just useful for sussing out the shape of the XML. Setup: >>> import lxml.etree as etree >>> book = etree.parse('protocol.xml').getroot() >>> dumper = LXML_Dumper(maxdepth=2) >>> dumper.dump(book) The Music Player Daemon protocol (/book): [title] (/book/title): The Music Player Daemon protocol General protocol syntax (/book/chapter[1]): [title] (/book/chapter[1]/title): General protocol syntax Requests (/book/chapter[1]/section[1]) Responses (/book/chapter[1]/section[2]) Command lists (/book/chapter[1]/section[3]) Ranges (/book/chapter[1]/section[4]) Command reference (/book/chapter[2]): [title] (/book/chapter[2]/title): Command reference [note] (/book/chapter[2]/note): Querying MPD's status (/book/chapter[2]/section[1]) Playback options (/book/chapter[2]/section[2]) Controlling playback (/book/chapter[2]/section[3]) The current playlist (/book/chapter[2]/section[4]) Stored playlists (/book/chapter[2]/section[5]) The music database (/book/chapter[2]/section[6]) Stickers (/book/chapter[2]/section[7]) Connection settings (/book/chapter[2]/section[8]) Audio output devices (/book/chapter[2]/section[9]) Reflection (/book/chapter[2]/section[10]) >>> for c in book.iterdescendants('section'): ... dumper.dump(c, maxdepth=0, rules='full') Requests (/book/chapter[1]/section[1]): Responses (/book/chapter[1]/section[2]): Command lists (/book/chapter[1]/section[3]): Ranges (/book/chapter[1]/section[4]): Querying MPD's status (/book/chapter[2]/section[1]): Playback options (/book/chapter[2]/section[2]): Controlling playback (/book/chapter[2]/section[3]): The current playlist (/book/chapter[2]/section[4]): Stored playlists (/book/chapter[2]/section[5]): The music database (/book/chapter[2]/section[6]): Stickers (/book/chapter[2]/section[7]): Connection settings (/book/chapter[2]/section[8]): Audio output devices (/book/chapter[2]/section[9]): Reflection (/book/chapter[2]/section[10]): """ # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'book': {'section': {'with_text': False}, 'para': {'linebreak': True}, None: {'recurse': True}}, 'full': {None: {'recurse': True}}} maxdepth = None width = 80 rules = rulesets['book'] def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `rules`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `maxdepth` and `rules` object keyword arguments can be overridden. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) maxdepth, rules = (kwargs.pop(a, getattr(self, a)) for a in ('maxdepth', 'rules')) if isinstance(rules, Mapping): pass elif isinstance(rules, basestring): rules = self.rulesets[rules] assert isinstance(rules, Mapping) def _dump(element, depth=0): for rule in rules.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) print self.format_element(element, depth, **kwargs) if recurse: if (maxdepth is None or maxdepth > depth): for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) def iter_unique_child_tags(self, root, tag): """Iterates through unique child tags for all instances of `tag`. Iteration starts at `root`. """ found_child_tags = set() instances = root.iterdescendants(tag) from itertools import chain child_nodes = chain.from_iterable(i.getchildren() for i in instances) child_tags = (n.tag for n in child_nodes) for t in child_tags: if t not in found_child_tags: found_child_tags.add(t) yield t def iter_tag_list(self, root): """List all unique tags at and under the `root` node.""" found_tags = set() tags = (n.tag for n in root.iterdescendants() if hasattr(n, 'tag')) for t in tags: if t not in found_tags: found_tags.add(t) yield t + + def build_tag_graph(self, root): + """Build a python-graph graph of the tag relationships.""" + from pygraph.classes.digraph import digraph + + g = digraph() + + tags = list(self.iter_tag_list(root)) + g.add_nodes(tags) + + for parent in tags: + for child in self.iter_unique_child_tags(root, parent): + g.add_edge((parent, child)) + + return g + + def write_graph(self, graph, filename, format='png'): + """Write a python-graph graph as an image. + + `format` can be any of those supported by pydot.Dot.write(). + """ + from pygraph.readwrite.dot import write + dotdata = write(graph) + + from pydot import graph_from_dot_data + dotgraph = graph_from_dot_data(dotdata) + dotgraph.write(filename, format=format) + + def write_tag_graph(self, root, filename, format='png'): + graph = self.build_tag_graph(root) + self.write_graph(graph, filename, format=format)
intuited/xmlearn
c69cf002a3a652837235aad4086d79d51e7417f1
add function to iterate unique tags
diff --git a/__init__.py b/__init__.py index 19b70ec..607e5f1 100644 --- a/__init__.py +++ b/__init__.py @@ -1,158 +1,167 @@ """Routines to parse mpd's protocol documentation.""" class LXML_Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. rules: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. For now, this function is just useful for sussing out the shape of the XML. Setup: >>> import lxml.etree as etree >>> book = etree.parse('protocol.xml').getroot() >>> dumper = LXML_Dumper(maxdepth=2) >>> dumper.dump(book) The Music Player Daemon protocol (/book): [title] (/book/title): The Music Player Daemon protocol General protocol syntax (/book/chapter[1]): [title] (/book/chapter[1]/title): General protocol syntax Requests (/book/chapter[1]/section[1]) Responses (/book/chapter[1]/section[2]) Command lists (/book/chapter[1]/section[3]) Ranges (/book/chapter[1]/section[4]) Command reference (/book/chapter[2]): [title] (/book/chapter[2]/title): Command reference [note] (/book/chapter[2]/note): Querying MPD's status (/book/chapter[2]/section[1]) Playback options (/book/chapter[2]/section[2]) Controlling playback (/book/chapter[2]/section[3]) The current playlist (/book/chapter[2]/section[4]) Stored playlists (/book/chapter[2]/section[5]) The music database (/book/chapter[2]/section[6]) Stickers (/book/chapter[2]/section[7]) Connection settings (/book/chapter[2]/section[8]) Audio output devices (/book/chapter[2]/section[9]) Reflection (/book/chapter[2]/section[10]) >>> for c in book.iterdescendants('section'): ... dumper.dump(c, maxdepth=0, rules='full') Requests (/book/chapter[1]/section[1]): Responses (/book/chapter[1]/section[2]): Command lists (/book/chapter[1]/section[3]): Ranges (/book/chapter[1]/section[4]): Querying MPD's status (/book/chapter[2]/section[1]): Playback options (/book/chapter[2]/section[2]): Controlling playback (/book/chapter[2]/section[3]): The current playlist (/book/chapter[2]/section[4]): Stored playlists (/book/chapter[2]/section[5]): The music database (/book/chapter[2]/section[6]): Stickers (/book/chapter[2]/section[7]): Connection settings (/book/chapter[2]/section[8]): Audio output devices (/book/chapter[2]/section[9]): Reflection (/book/chapter[2]/section[10]): """ # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'book': {'section': {'with_text': False}, 'para': {'linebreak': True}, None: {'recurse': True}}, 'full': {None: {'recurse': True}}} maxdepth = None width = 80 rules = rulesets['book'] def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `rules`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `maxdepth` and `rules` object keyword arguments can be overridden. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) maxdepth, rules = (kwargs.pop(a, getattr(self, a)) for a in ('maxdepth', 'rules')) if isinstance(rules, Mapping): pass elif isinstance(rules, basestring): rules = self.rulesets[rules] assert isinstance(rules, Mapping) def _dump(element, depth=0): for rule in rules.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) print self.format_element(element, depth, **kwargs) if recurse: if (maxdepth is None or maxdepth > depth): for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) def iter_unique_child_tags(self, root, tag): """Iterates through unique child tags for all instances of `tag`. Iteration starts at `root`. """ found_child_tags = set() instances = root.iterdescendants(tag) from itertools import chain child_nodes = chain.from_iterable(i.getchildren() for i in instances) child_tags = (n.tag for n in child_nodes) for t in child_tags: if t not in found_child_tags: found_child_tags.add(t) yield t + + def iter_tag_list(self, root): + """List all unique tags at and under the `root` node.""" + found_tags = set() + tags = (n.tag for n in root.iterdescendants() if hasattr(n, 'tag')) + for t in tags: + if t not in found_tags: + found_tags.add(t) + yield t
intuited/xmlearn
3f663ce023013e639173fc322de67f248c7ca7a7
minor documentation fixup
diff --git a/__init__.py b/__init__.py index 71ddf71..19b70ec 100644 --- a/__init__.py +++ b/__init__.py @@ -1,158 +1,158 @@ """Routines to parse mpd's protocol documentation.""" class LXML_Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. rules: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. For now, this function is just useful for sussing out the shape of the XML. Setup: >>> import lxml.etree as etree >>> book = etree.parse('protocol.xml').getroot() >>> dumper = LXML_Dumper(maxdepth=2) >>> dumper.dump(book) The Music Player Daemon protocol (/book): [title] (/book/title): The Music Player Daemon protocol General protocol syntax (/book/chapter[1]): [title] (/book/chapter[1]/title): General protocol syntax Requests (/book/chapter[1]/section[1]) Responses (/book/chapter[1]/section[2]) Command lists (/book/chapter[1]/section[3]) Ranges (/book/chapter[1]/section[4]) Command reference (/book/chapter[2]): [title] (/book/chapter[2]/title): Command reference [note] (/book/chapter[2]/note): Querying MPD's status (/book/chapter[2]/section[1]) Playback options (/book/chapter[2]/section[2]) Controlling playback (/book/chapter[2]/section[3]) The current playlist (/book/chapter[2]/section[4]) Stored playlists (/book/chapter[2]/section[5]) The music database (/book/chapter[2]/section[6]) Stickers (/book/chapter[2]/section[7]) Connection settings (/book/chapter[2]/section[8]) Audio output devices (/book/chapter[2]/section[9]) Reflection (/book/chapter[2]/section[10]) >>> for c in book.iterdescendants('section'): ... dumper.dump(c, maxdepth=0, rules='full') Requests (/book/chapter[1]/section[1]): Responses (/book/chapter[1]/section[2]): Command lists (/book/chapter[1]/section[3]): Ranges (/book/chapter[1]/section[4]): Querying MPD's status (/book/chapter[2]/section[1]): Playback options (/book/chapter[2]/section[2]): Controlling playback (/book/chapter[2]/section[3]): The current playlist (/book/chapter[2]/section[4]): Stored playlists (/book/chapter[2]/section[5]): The music database (/book/chapter[2]/section[6]): Stickers (/book/chapter[2]/section[7]): Connection settings (/book/chapter[2]/section[8]): Audio output devices (/book/chapter[2]/section[9]): Reflection (/book/chapter[2]/section[10]): """ # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'book': {'section': {'with_text': False}, 'para': {'linebreak': True}, None: {'recurse': True}}, 'full': {None: {'recurse': True}}} maxdepth = None width = 80 rules = rulesets['book'] def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `rules`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `maxdepth` and `rules` object keyword arguments can be overridden. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) maxdepth, rules = (kwargs.pop(a, getattr(self, a)) for a in ('maxdepth', 'rules')) if isinstance(rules, Mapping): pass elif isinstance(rules, basestring): rules = self.rulesets[rules] assert isinstance(rules, Mapping) def _dump(element, depth=0): for rule in rules.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) print self.format_element(element, depth, **kwargs) if recurse: if (maxdepth is None or maxdepth > depth): for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) def iter_unique_child_tags(self, root, tag): - """Iterates through unique child tags for all instances of tag. + """Iterates through unique child tags for all instances of `tag`. Iteration starts at `root`. """ found_child_tags = set() instances = root.iterdescendants(tag) from itertools import chain child_nodes = chain.from_iterable(i.getchildren() for i in instances) child_tags = (n.tag for n in child_nodes) for t in child_tags: if t not in found_child_tags: found_child_tags.add(t) yield t
intuited/xmlearn
c7f5329e3f59732c1e3a1b4ad026b6c606ef124b
fix signature of iter_unique_child_tags. it works now.
diff --git a/__init__.py b/__init__.py index b905a1b..71ddf71 100644 --- a/__init__.py +++ b/__init__.py @@ -1,158 +1,158 @@ """Routines to parse mpd's protocol documentation.""" class LXML_Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. rules: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. For now, this function is just useful for sussing out the shape of the XML. Setup: >>> import lxml.etree as etree >>> book = etree.parse('protocol.xml').getroot() >>> dumper = LXML_Dumper(maxdepth=2) >>> dumper.dump(book) The Music Player Daemon protocol (/book): [title] (/book/title): The Music Player Daemon protocol General protocol syntax (/book/chapter[1]): [title] (/book/chapter[1]/title): General protocol syntax Requests (/book/chapter[1]/section[1]) Responses (/book/chapter[1]/section[2]) Command lists (/book/chapter[1]/section[3]) Ranges (/book/chapter[1]/section[4]) Command reference (/book/chapter[2]): [title] (/book/chapter[2]/title): Command reference [note] (/book/chapter[2]/note): Querying MPD's status (/book/chapter[2]/section[1]) Playback options (/book/chapter[2]/section[2]) Controlling playback (/book/chapter[2]/section[3]) The current playlist (/book/chapter[2]/section[4]) Stored playlists (/book/chapter[2]/section[5]) The music database (/book/chapter[2]/section[6]) Stickers (/book/chapter[2]/section[7]) Connection settings (/book/chapter[2]/section[8]) Audio output devices (/book/chapter[2]/section[9]) Reflection (/book/chapter[2]/section[10]) >>> for c in book.iterdescendants('section'): ... dumper.dump(c, maxdepth=0, rules='full') Requests (/book/chapter[1]/section[1]): Responses (/book/chapter[1]/section[2]): Command lists (/book/chapter[1]/section[3]): Ranges (/book/chapter[1]/section[4]): Querying MPD's status (/book/chapter[2]/section[1]): Playback options (/book/chapter[2]/section[2]): Controlling playback (/book/chapter[2]/section[3]): The current playlist (/book/chapter[2]/section[4]): Stored playlists (/book/chapter[2]/section[5]): The music database (/book/chapter[2]/section[6]): Stickers (/book/chapter[2]/section[7]): Connection settings (/book/chapter[2]/section[8]): Audio output devices (/book/chapter[2]/section[9]): Reflection (/book/chapter[2]/section[10]): """ # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'book': {'section': {'with_text': False}, 'para': {'linebreak': True}, None: {'recurse': True}}, 'full': {None: {'recurse': True}}} maxdepth = None width = 80 rules = rulesets['book'] def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `rules`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `maxdepth` and `rules` object keyword arguments can be overridden. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) maxdepth, rules = (kwargs.pop(a, getattr(self, a)) for a in ('maxdepth', 'rules')) if isinstance(rules, Mapping): pass elif isinstance(rules, basestring): rules = self.rulesets[rules] assert isinstance(rules, Mapping) def _dump(element, depth=0): for rule in rules.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) print self.format_element(element, depth, **kwargs) if recurse: if (maxdepth is None or maxdepth > depth): for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) - def iter_unique_child_tags(root, tag): + def iter_unique_child_tags(self, root, tag): """Iterates through unique child tags for all instances of tag. Iteration starts at `root`. """ found_child_tags = set() instances = root.iterdescendants(tag) from itertools import chain child_nodes = chain.from_iterable(i.getchildren() for i in instances) child_tags = (n.tag for n in child_nodes) for t in child_tags: if t not in found_child_tags: found_child_tags.add(t) yield t
intuited/xmlearn
c4d1e885e8e9d5358cd7fdc7cc59251cfacbc87b
revise docstring example
diff --git a/__init__.py b/__init__.py index 9c6f09d..b905a1b 100644 --- a/__init__.py +++ b/__init__.py @@ -1,142 +1,158 @@ """Routines to parse mpd's protocol documentation.""" class LXML_Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. rules: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. For now, this function is just useful for sussing out the shape of the XML. Setup: >>> import lxml.etree as etree >>> book = etree.parse('protocol.xml').getroot() >>> dumper = LXML_Dumper(maxdepth=2) >>> dumper.dump(book) - >>> [dumper.dump(c, maxdepth=1, rules='full') - ... for c in book.iterfind('chapter')] + The Music Player Daemon protocol (/book): + [title] (/book/title): The Music Player Daemon protocol General protocol syntax (/book/chapter[1]): [title] (/book/chapter[1]/title): General protocol syntax - Requests (/book/chapter[1]/section[1]): - Responses (/book/chapter[1]/section[2]): - Command lists (/book/chapter[1]/section[3]): - Ranges (/book/chapter[1]/section[4]): + Requests (/book/chapter[1]/section[1]) + Responses (/book/chapter[1]/section[2]) + Command lists (/book/chapter[1]/section[3]) + Ranges (/book/chapter[1]/section[4]) Command reference (/book/chapter[2]): [title] (/book/chapter[2]/title): Command reference [note] (/book/chapter[2]/note): - Querying MPD's status (/book/chapter[2]/section[1]): - Playback options (/book/chapter[2]/section[2]): - Controlling playback (/book/chapter[2]/section[3]): - The current playlist (/book/chapter[2]/section[4]): - Stored playlists (/book/chapter[2]/section[5]): - The music database (/book/chapter[2]/section[6]): - Stickers (/book/chapter[2]/section[7]): - Connection settings (/book/chapter[2]/section[8]): - Audio output devices (/book/chapter[2]/section[9]): - Reflection (/book/chapter[2]/section[10]): + Querying MPD's status (/book/chapter[2]/section[1]) + Playback options (/book/chapter[2]/section[2]) + Controlling playback (/book/chapter[2]/section[3]) + The current playlist (/book/chapter[2]/section[4]) + Stored playlists (/book/chapter[2]/section[5]) + The music database (/book/chapter[2]/section[6]) + Stickers (/book/chapter[2]/section[7]) + Connection settings (/book/chapter[2]/section[8]) + Audio output devices (/book/chapter[2]/section[9]) + Reflection (/book/chapter[2]/section[10]) + >>> for c in book.iterdescendants('section'): + ... dumper.dump(c, maxdepth=0, rules='full') + Requests (/book/chapter[1]/section[1]): + Responses (/book/chapter[1]/section[2]): + Command lists (/book/chapter[1]/section[3]): + Ranges (/book/chapter[1]/section[4]): + Querying MPD's status (/book/chapter[2]/section[1]): + Playback options (/book/chapter[2]/section[2]): + Controlling playback (/book/chapter[2]/section[3]): + The current playlist (/book/chapter[2]/section[4]): + Stored playlists (/book/chapter[2]/section[5]): + The music database (/book/chapter[2]/section[6]): + Stickers (/book/chapter[2]/section[7]): + Connection settings (/book/chapter[2]/section[8]): + Audio output devices (/book/chapter[2]/section[9]): + Reflection (/book/chapter[2]/section[10]): """ # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'book': {'section': {'with_text': False}, 'para': {'linebreak': True}, None: {'recurse': True}}, 'full': {None: {'recurse': True}}} maxdepth = None width = 80 rules = rulesets['book'] def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `rules`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `maxdepth` and `rules` object keyword arguments can be overridden. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) maxdepth, rules = (kwargs.pop(a, getattr(self, a)) for a in ('maxdepth', 'rules')) if isinstance(rules, Mapping): pass elif isinstance(rules, basestring): rules = self.rulesets[rules] assert isinstance(rules, Mapping) def _dump(element, depth=0): for rule in rules.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) print self.format_element(element, depth, **kwargs) if recurse: if (maxdepth is None or maxdepth > depth): for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) def iter_unique_child_tags(root, tag): """Iterates through unique child tags for all instances of tag. Iteration starts at `root`. """ found_child_tags = set() instances = root.iterdescendants(tag) from itertools import chain child_nodes = chain.from_iterable(i.getchildren() for i in instances) child_tags = (n.tag for n in child_nodes) for t in child_tags: if t not in found_child_tags: found_child_tags.add(t) yield t
intuited/xmlearn
af7f13a2ee6c1c9d1381e3e12eddee25cb4f6afc
add function to list unique child tags for a tag.
diff --git a/__init__.py b/__init__.py index f433b7b..9c6f09d 100644 --- a/__init__.py +++ b/__init__.py @@ -1,127 +1,142 @@ """Routines to parse mpd's protocol documentation.""" class LXML_Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. rules: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. For now, this function is just useful for sussing out the shape of the XML. Setup: >>> import lxml.etree as etree >>> book = etree.parse('protocol.xml').getroot() >>> dumper = LXML_Dumper(maxdepth=2) >>> dumper.dump(book) >>> [dumper.dump(c, maxdepth=1, rules='full') ... for c in book.iterfind('chapter')] General protocol syntax (/book/chapter[1]): [title] (/book/chapter[1]/title): General protocol syntax Requests (/book/chapter[1]/section[1]): Responses (/book/chapter[1]/section[2]): Command lists (/book/chapter[1]/section[3]): Ranges (/book/chapter[1]/section[4]): Command reference (/book/chapter[2]): [title] (/book/chapter[2]/title): Command reference [note] (/book/chapter[2]/note): Querying MPD's status (/book/chapter[2]/section[1]): Playback options (/book/chapter[2]/section[2]): Controlling playback (/book/chapter[2]/section[3]): The current playlist (/book/chapter[2]/section[4]): Stored playlists (/book/chapter[2]/section[5]): The music database (/book/chapter[2]/section[6]): Stickers (/book/chapter[2]/section[7]): Connection settings (/book/chapter[2]/section[8]): Audio output devices (/book/chapter[2]/section[9]): Reflection (/book/chapter[2]/section[10]): """ # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'book': {'section': {'with_text': False}, 'para': {'linebreak': True}, None: {'recurse': True}}, 'full': {None: {'recurse': True}}} maxdepth = None width = 80 rules = rulesets['book'] def __init__(self, **kwargs): """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): """Wrap the text with an indent relative to the `depth` keyword arg. The text is indented 4 spaces for each level of depth. Wrapped lines are indented an extra 2 spaces. """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) def dump(self, element, **kwargs): """Dump `element` according to `rules`. Keyword arguments: depth: the initial depth of the dump. Normally this will be 0. Additionally, the `maxdepth` and `rules` object keyword arguments can be overridden. """ from copy import copy from collections import Mapping depth = kwargs.pop('depth', 0) maxdepth, rules = (kwargs.pop(a, getattr(self, a)) for a in ('maxdepth', 'rules')) if isinstance(rules, Mapping): pass elif isinstance(rules, basestring): rules = self.rulesets[rules] assert isinstance(rules, Mapping) def _dump(element, depth=0): for rule in rules.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) print self.format_element(element, depth, **kwargs) if recurse: if (maxdepth is None or maxdepth > depth): for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) + + def iter_unique_child_tags(root, tag): + """Iterates through unique child tags for all instances of tag. + + Iteration starts at `root`. + """ + found_child_tags = set() + instances = root.iterdescendants(tag) + from itertools import chain + child_nodes = chain.from_iterable(i.getchildren() for i in instances) + child_tags = (n.tag for n in child_nodes) + for t in child_tags: + if t not in found_child_tags: + found_child_tags.add(t) + yield t
intuited/xmlearn
70e817f91c9bfc342744a3b9c55b56bda5c6c53a
add option to override object properties when calling `dump`
diff --git a/__init__.py b/__init__.py index 533276d..f433b7b 100644 --- a/__init__.py +++ b/__init__.py @@ -1,91 +1,127 @@ """Routines to parse mpd's protocol documentation.""" class LXML_Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. + rules: either a string matching one of the keys of rulesets, + or a Mapping containing such a ruleset. + + For now, this function is just useful for sussing out the shape of the XML. + + Setup: + >>> import lxml.etree as etree + >>> book = etree.parse('protocol.xml').getroot() + >>> dumper = LXML_Dumper(maxdepth=2) + >>> dumper.dump(book) + >>> [dumper.dump(c, maxdepth=1, rules='full') + ... for c in book.iterfind('chapter')] + General protocol syntax (/book/chapter[1]): + [title] (/book/chapter[1]/title): General protocol syntax + Requests (/book/chapter[1]/section[1]): + Responses (/book/chapter[1]/section[2]): + Command lists (/book/chapter[1]/section[3]): + Ranges (/book/chapter[1]/section[4]): + Command reference (/book/chapter[2]): + [title] (/book/chapter[2]/title): Command reference + [note] (/book/chapter[2]/note): + Querying MPD's status (/book/chapter[2]/section[1]): + Playback options (/book/chapter[2]/section[2]): + Controlling playback (/book/chapter[2]/section[3]): + The current playlist (/book/chapter[2]/section[4]): + Stored playlists (/book/chapter[2]/section[5]): + The music database (/book/chapter[2]/section[6]): + Stickers (/book/chapter[2]/section[7]): + Connection settings (/book/chapter[2]/section[8]): + Audio output devices (/book/chapter[2]/section[9]): + Reflection (/book/chapter[2]/section[10]): + """ + # Each ruleset maps tags to kwargs for `format_element`. + rulesets = {'book': {'section': {'with_text': False}, + 'para': {'linebreak': True}, + None: {'recurse': True}}, + 'full': {None: {'recurse': True}}} + + maxdepth = None + width = 80 + rules = rulesets['book'] + def __init__(self, **kwargs): + """Initialize object attributes documented in the class docstring.""" self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): + """Wrap the text with an indent relative to the `depth` keyword arg. + + The text is indented 4 spaces for each level of depth. + Wrapped lines are indented an extra 2 spaces. + """ from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) - # Each ruleset maps tags to kwargs for `format_element`. - rulesets = {'book': {'section': {'with_text': False}, - 'para': {'linebreak': True}, - None: {'recurse': True}}, - 'full': {None: {'recurse': True}}} - - def dump(self, element, rules=rulesets['book'], depth=0): + def dump(self, element, **kwargs): """Dump `element` according to `rules`. Keyword arguments: - rules: either a string matching one of the keys of rulesets, - or a Mapping containing such a ruleset. - depth: the initial depth of the dump. + depth: the initial depth of the dump. Normally this will be 0. + + Additionally, the `maxdepth` and `rules` object keyword arguments + can be overridden. """ from copy import copy from collections import Mapping + depth = kwargs.pop('depth', 0) + maxdepth, rules = (kwargs.pop(a, getattr(self, a)) + for a in ('maxdepth', 'rules')) + if isinstance(rules, Mapping): pass elif isinstance(rules, basestring): rules = self.rulesets[rules] assert isinstance(rules, Mapping) def _dump(element, depth=0): for rule in rules.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) print self.format_element(element, depth, **kwargs) if recurse: - if (hasattr(self, 'maxdepth') and self.maxdepth >= depth - or not hasattr(self, 'maxdepth') - ): + if (maxdepth is None or maxdepth > depth): for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) - -##-- if element.tag == 'section': -##-- print self.format_element(element, depth, with_text=False) -##-- elif element.tag == 'para': -##-- print self.format_element(element, depth, linebreak=True) -##-- else: -##-- print self.format_element(element, depth) -##-- for child in element.getchildren(): -##-- _dump(child, depth + 1)
intuited/xmlearn
5bb97b3aca0d5f51494edeb8d48e864fb4184dd0
remove pretty-printing approach code
diff --git a/__init__.py b/__init__.py index e805b1f..533276d 100644 --- a/__init__.py +++ b/__init__.py @@ -1,161 +1,91 @@ """Routines to parse mpd's protocol documentation.""" -from pprint import PrettyPrinter as _PrettyPrinter -from xml.etree import ElementTree as _ElementTree - -class TagsPrinter(_PrettyPrinter): - """Prettyprint tags from etree elements. - - This doesn't really work very well.""" - - from pprint import _recursion, _safe_repr, _commajoin - _recursion = staticmethod(_recursion) - _safe_repr = staticmethod(_safe_repr) - _commajoin = staticmethod(_commajoin) - - def format(self, object, context, maxlevels, level): - if isinstance(object, _ElementTree._ElementInterface): - return self._format_element(object, context, - maxlevels, level) - else: - return self._safe_repr(object, context, maxlevels, level) - - def _format_element(self, object, context, maxlevels, level): - """Handle formatting of ElementTree._ElementInterface objects.""" - # This code is based on the case of pprint._safe_repr - # which handles list and tuple instances. - tag = object.tag - if len(object) == 1: - format = tag + ': (%s,)' - else: - if len(object) == 0: - return tag, False, False - format = tag + ': (%s)' - objid = id(object) - if maxlevels and level >= maxlevels: - return format % "...", False, objid in context - if objid in context: - return self._recursion(object), False, True - context[objid] = 1 - readable = False - recursive = False - components = [] - append = components.append - level += 1 - for o in object: - orepr, oreadable, orecur = self.format(o, context, maxlevels, - level) - append(orepr) - if not oreadable: - readable = False - if orecur: - recursive = True - del context[objid] - return format % self._commajoin(components), readable, recursive - -class CommandReflection(_ElementTree.ElementTree): - """Provides command info based on the contents of a protocol.xml file.""" - def __init__(self, source): - _ElementTree.ElementTree.__init__(self, None, source) - - def dump_commands(self): - return TagsPrinter().pformat(self.getroot()) - - -# A new approach. This seems to be working better. class LXML_Dumper(object): """Dump an lxml.etree tree starting at `element`. Attributes: maxdepth: the maximum recursion level. width: the width at which text will be wrapped. """ def __init__(self, **kwargs): self.__dict__.update(kwargs) def relwrap(self, *args, **kwargs): from textwrap import wrap depth = kwargs.pop('depth', 0) wrap_kwargs = dict({'initial_indent': ' ' * depth, 'subsequent_indent': ' ' * depth + ' '}) if hasattr(self, 'width'): wrap_kwargs.update(width=self.width) wrap_kwargs.update(kwargs) return "\n".join(wrap(*args, **wrap_kwargs)) def format_element(self, element, depth, linebreak=False, with_text=True): from textwrap import dedent title = getattr(element.find('title'), 'text', '') title = title if title else '[{0}]'.format(element.tag) path = element.getroottree().getpath(element) eltext = getattr(element, 'text', '') eltext = dedent(eltext if eltext else '') if linebreak: summary = "{0} ({1}):".format(title, path) return "\n".join([self.relwrap(summary, depth=depth), self.relwrap(eltext, depth=depth+1)]) else: fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" return self.relwrap(fmt.format(title, path, eltext), depth=depth) # Each ruleset maps tags to kwargs for `format_element`. rulesets = {'book': {'section': {'with_text': False}, 'para': {'linebreak': True}, None: {'recurse': True}}, 'full': {None: {'recurse': True}}} def dump(self, element, rules=rulesets['book'], depth=0): """Dump `element` according to `rules`. Keyword arguments: rules: either a string matching one of the keys of rulesets, or a Mapping containing such a ruleset. depth: the initial depth of the dump. """ from copy import copy from collections import Mapping if isinstance(rules, Mapping): pass elif isinstance(rules, basestring): rules = self.rulesets[rules] assert isinstance(rules, Mapping) def _dump(element, depth=0): for rule in rules.iteritems(): if rule[0] == None: default = copy(rule[1]) elif rule[0] == element.tag: kwargs = copy(rule[1]) break else: assert vars().has_key('default') kwargs = default recurse = kwargs.pop('recurse', False) print self.format_element(element, depth, **kwargs) if recurse: if (hasattr(self, 'maxdepth') and self.maxdepth >= depth or not hasattr(self, 'maxdepth') ): for child in element.getchildren(): _dump(child, depth + 1) _dump(element, depth=depth) ##-- if element.tag == 'section': ##-- print self.format_element(element, depth, with_text=False) ##-- elif element.tag == 'para': ##-- print self.format_element(element, depth, linebreak=True) ##-- else: ##-- print self.format_element(element, depth) ##-- for child in element.getchildren(): ##-- _dump(child, depth + 1) - - - -if __name__ == '__main__': - from sys import argv - with open(argv[1], 'r') as f: - print CommandReflection(f).dump_commands()
intuited/xmlearn
0017f2854135a700553682f88d39a661a99eec42
initial working version of the LXML_Dumper class.
diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..e805b1f --- /dev/null +++ b/__init__.py @@ -0,0 +1,161 @@ +"""Routines to parse mpd's protocol documentation.""" +from pprint import PrettyPrinter as _PrettyPrinter + +from xml.etree import ElementTree as _ElementTree + +class TagsPrinter(_PrettyPrinter): + """Prettyprint tags from etree elements. + + This doesn't really work very well.""" + + from pprint import _recursion, _safe_repr, _commajoin + _recursion = staticmethod(_recursion) + _safe_repr = staticmethod(_safe_repr) + _commajoin = staticmethod(_commajoin) + + def format(self, object, context, maxlevels, level): + if isinstance(object, _ElementTree._ElementInterface): + return self._format_element(object, context, + maxlevels, level) + else: + return self._safe_repr(object, context, maxlevels, level) + + def _format_element(self, object, context, maxlevels, level): + """Handle formatting of ElementTree._ElementInterface objects.""" + # This code is based on the case of pprint._safe_repr + # which handles list and tuple instances. + tag = object.tag + if len(object) == 1: + format = tag + ': (%s,)' + else: + if len(object) == 0: + return tag, False, False + format = tag + ': (%s)' + objid = id(object) + if maxlevels and level >= maxlevels: + return format % "...", False, objid in context + if objid in context: + return self._recursion(object), False, True + context[objid] = 1 + readable = False + recursive = False + components = [] + append = components.append + level += 1 + for o in object: + orepr, oreadable, orecur = self.format(o, context, maxlevels, + level) + append(orepr) + if not oreadable: + readable = False + if orecur: + recursive = True + del context[objid] + return format % self._commajoin(components), readable, recursive + +class CommandReflection(_ElementTree.ElementTree): + """Provides command info based on the contents of a protocol.xml file.""" + def __init__(self, source): + _ElementTree.ElementTree.__init__(self, None, source) + + def dump_commands(self): + return TagsPrinter().pformat(self.getroot()) + + +# A new approach. This seems to be working better. +class LXML_Dumper(object): + """Dump an lxml.etree tree starting at `element`. + + Attributes: + maxdepth: the maximum recursion level. + width: the width at which text will be wrapped. + """ + + def __init__(self, **kwargs): + self.__dict__.update(kwargs) + + def relwrap(self, *args, **kwargs): + from textwrap import wrap + depth = kwargs.pop('depth', 0) + wrap_kwargs = dict({'initial_indent': ' ' * depth, + 'subsequent_indent': ' ' * depth + ' '}) + if hasattr(self, 'width'): + wrap_kwargs.update(width=self.width) + wrap_kwargs.update(kwargs) + return "\n".join(wrap(*args, **wrap_kwargs)) + + def format_element(self, element, depth, linebreak=False, with_text=True): + from textwrap import dedent + title = getattr(element.find('title'), 'text', '') + title = title if title else '[{0}]'.format(element.tag) + path = element.getroottree().getpath(element) + eltext = getattr(element, 'text', '') + eltext = dedent(eltext if eltext else '') + if linebreak: + summary = "{0} ({1}):".format(title, path) + return "\n".join([self.relwrap(summary, depth=depth), + self.relwrap(eltext, depth=depth+1)]) + else: + fmt = "{0} ({1}): {2}" if with_text else "{0} ({1})" + return self.relwrap(fmt.format(title, path, eltext), depth=depth) + + # Each ruleset maps tags to kwargs for `format_element`. + rulesets = {'book': {'section': {'with_text': False}, + 'para': {'linebreak': True}, + None: {'recurse': True}}, + 'full': {None: {'recurse': True}}} + + def dump(self, element, rules=rulesets['book'], depth=0): + """Dump `element` according to `rules`. + + Keyword arguments: + rules: either a string matching one of the keys of rulesets, + or a Mapping containing such a ruleset. + depth: the initial depth of the dump. + """ + from copy import copy + from collections import Mapping + + if isinstance(rules, Mapping): + pass + elif isinstance(rules, basestring): + rules = self.rulesets[rules] + assert isinstance(rules, Mapping) + + def _dump(element, depth=0): + for rule in rules.iteritems(): + if rule[0] == None: + default = copy(rule[1]) + elif rule[0] == element.tag: + kwargs = copy(rule[1]) + break + else: + assert vars().has_key('default') + kwargs = default + + recurse = kwargs.pop('recurse', False) + print self.format_element(element, depth, **kwargs) + if recurse: + if (hasattr(self, 'maxdepth') and self.maxdepth >= depth + or not hasattr(self, 'maxdepth') + ): + for child in element.getchildren(): + _dump(child, depth + 1) + + _dump(element, depth=depth) + +##-- if element.tag == 'section': +##-- print self.format_element(element, depth, with_text=False) +##-- elif element.tag == 'para': +##-- print self.format_element(element, depth, linebreak=True) +##-- else: +##-- print self.format_element(element, depth) +##-- for child in element.getchildren(): +##-- _dump(child, depth + 1) + + + +if __name__ == '__main__': + from sys import argv + with open(argv[1], 'r') as f: + print CommandReflection(f).dump_commands()
ribbit-tnt/ribbit-sdk-downloads
4d9bcf8cbf719d25cb07fa7cd603c9524383b4d5
Added binary packages for .NET, Flash, Java, and Silverlight. Added source packages for JS and PHP.
diff --git a/binary/ribbit_dotnet_1.6.0.zip b/binary/ribbit_dotnet_1.6.0.zip new file mode 100644 index 0000000..e6c3466 Binary files /dev/null and b/binary/ribbit_dotnet_1.6.0.zip differ diff --git a/binary/ribbit_flash_2.6.0.zip b/binary/ribbit_flash_2.6.0.zip new file mode 100644 index 0000000..982501f Binary files /dev/null and b/binary/ribbit_flash_2.6.0.zip differ diff --git a/binary/ribbit_flash_2.7.0.zip b/binary/ribbit_flash_2.7.0.zip new file mode 100644 index 0000000..f9347f8 Binary files /dev/null and b/binary/ribbit_flash_2.7.0.zip differ diff --git a/binary/ribbit_java_1.6.0.zip b/binary/ribbit_java_1.6.0.zip new file mode 100644 index 0000000..ab84eea Binary files /dev/null and b/binary/ribbit_java_1.6.0.zip differ diff --git a/binary/ribbit_silverlight_1.6.0.zip b/binary/ribbit_silverlight_1.6.0.zip new file mode 100644 index 0000000..89a0796 Binary files /dev/null and b/binary/ribbit_silverlight_1.6.0.zip differ diff --git a/source/ribbit_javascript_1.6.0.zip b/source/ribbit_javascript_1.6.0.zip new file mode 100644 index 0000000..bf9dbde Binary files /dev/null and b/source/ribbit_javascript_1.6.0.zip differ diff --git a/source/ribbit_php_1.6.0.zip b/source/ribbit_php_1.6.0.zip new file mode 100644 index 0000000..ed924dc Binary files /dev/null and b/source/ribbit_php_1.6.0.zip differ
kueda/inat-taxonomic_flickr_tagger
991843059f25e499419c9e0874548999fcd6a591
Added link to userscripts.org.
diff --git a/README b/README index d87ee88..c8e9d70 100644 --- a/README +++ b/README @@ -1,4 +1,8 @@ The is a Greasmonkey script that inserts a link to the iNaturalist Taxonomic Flickr Tagger (http://inaturalist.org/taxa/flickr_tagger) on Flickr photo pages. It's based on the "Flickr on Black" Greasemonkey script by Simon Whitaker (http://userscripts.org/scripts/show/9523). + +This script is also available on userscripts.org: + +http://userscripts.org/scripts/show/46129
kueda/inat-taxonomic_flickr_tagger
c11536c9109c7a95a37969704d438f443e8ac6d2
Added the license to the script, updated the description.
diff --git a/README b/README index a68f3fc..d87ee88 100644 --- a/README +++ b/README @@ -1,4 +1,4 @@ The is a Greasmonkey script that inserts a link to the iNaturalist Taxonomic -Flickr Tagger on Flickr photo pages. It's based on the "Flickr on Black" -Greasemonkey script by Simon Whitaker // -(http://userscripts.org/scripts/show/9523). +Flickr Tagger (http://inaturalist.org/taxa/flickr_tagger) on Flickr photo +pages. It's based on the "Flickr on Black" Greasemonkey script by Simon +Whitaker (http://userscripts.org/scripts/show/9523). diff --git a/inat-taxonomic_flickr_tagger.js b/inat-taxonomic_flickr_tagger.js index b41445e..d1f14d2 100644 --- a/inat-taxonomic_flickr_tagger.js +++ b/inat-taxonomic_flickr_tagger.js @@ -1,25 +1,50 @@ // ==UserScript== // @name iNaturalist Taxonomic Flickr Tagger -// @description Adds "Add taxonomic tags from iNat" links to a Flickr photo page +// @description Adds a link to the iNaturalist Taxonomic Flickr Tagger to Flickr photo pages. // @namespace http://inaturalist.org/taxa/flickr_tagger // @include http://flickr.com/photos/* // @include http://www.flickr.com/photos/* // Based upon "Flickr on Black" by Simon Whitaker -// (http://userscripts.org/scripts/show/9523) +// (http://userscripts.org/scripts/show/9523). +// This script is also available on GitHub: +// http://github.com/kueda/inat-taxonomic_flickr_tagger/ // ==/UserScript== + +// The MIT License +// +// Copyright (c) 2009 Ken-ichi Ueda +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + ( function(){ if (document.getElementById("button_bar")) { pid = location.pathname.split('/')[3]; var container = document.createElement("div"); container.setAttribute("id", "taxaonomictagadder"); container.setAttribute("style", "margin-top: 10px"); var link = '<a href="http://inaturalist.org/taxa/flickr_tagger?flickr_photo_id=' + pid + '" style="text-decoration: none;" target="_new">Add taxonomic tags from iNaturalist.org</a>'; container.innerHTML = link; var tagList = document.getElementsByClassName('TagList')[0]; tagList.appendChild(container); } } )();
kueda/inat-taxonomic_flickr_tagger
a0c2eb82685e6c1e41230bc96217dd2401fa0c9f
Ok, this time I REALLY added the LICENSE and script.
diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..ab834be --- /dev/null +++ b/LICENSE @@ -0,0 +1,24 @@ +iNaturalist Taxonomic Flickr Tagger License +---------------------------------------------------------------- + +The MIT License + +Copyright (c) 2009 Ken-ichi Ueda + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/inat-taxonomic_flickr_tagger.js b/inat-taxonomic_flickr_tagger.js new file mode 100644 index 0000000..b41445e --- /dev/null +++ b/inat-taxonomic_flickr_tagger.js @@ -0,0 +1,25 @@ +// ==UserScript== +// @name iNaturalist Taxonomic Flickr Tagger +// @description Adds "Add taxonomic tags from iNat" links to a Flickr photo page +// @namespace http://inaturalist.org/taxa/flickr_tagger +// @include http://flickr.com/photos/* +// @include http://www.flickr.com/photos/* +// Based upon "Flickr on Black" by Simon Whitaker +// (http://userscripts.org/scripts/show/9523) +// ==/UserScript== +( + function(){ + if (document.getElementById("button_bar")) { + pid = location.pathname.split('/')[3]; + + var container = document.createElement("div"); + container.setAttribute("id", "taxaonomictagadder"); + container.setAttribute("style", "margin-top: 10px"); + var link = '<a href="http://inaturalist.org/taxa/flickr_tagger?flickr_photo_id=' + pid + '" style="text-decoration: none;" target="_new">Add taxonomic tags from iNaturalist.org</a>'; + container.innerHTML = link; + + var tagList = document.getElementsByClassName('TagList')[0]; + tagList.appendChild(container); + } + } +)();
kueda/inat-taxonomic_flickr_tagger
c44d574aeed50b549482f67a602944221eb2eac5
Added the Greasemonkey script, updated the README, and added a license.
diff --git a/README b/README index e69de29..a68f3fc 100644 --- a/README +++ b/README @@ -0,0 +1,4 @@ +The is a Greasmonkey script that inserts a link to the iNaturalist Taxonomic +Flickr Tagger on Flickr photo pages. It's based on the "Flickr on Black" +Greasemonkey script by Simon Whitaker // +(http://userscripts.org/scripts/show/9523).
spr1ng/Crawler
885ddffca9b139fcbff058ae20c3ab963a460795
last changes
diff --git a/.svn/entries b/.svn/entries index 901263d..e52d8a6 100644 --- a/.svn/entries +++ b/.svn/entries @@ -1,164 +1,164 @@ 10 dir -70 +93 svn://localhost/spr1ngsvn/TheEye/Eye svn://localhost/spr1ngsvn/TheEye -2010-07-08T03:48:08.935715Z -70 -spr1ng +2010-07-08T05:31:17.764496Z +76 +stream has-props 8763ed6d-9318-4032-b958-c511fcb819a9 () dist dir nbproject dir src dir manifest.mf file 2010-06-28T07:30:17.494569Z d6fe4af2f67849f1c01635b0ed4c443d 2010-06-28T07:29:35.843368Z 10 spr1ng 82 libs dir db.db4o file delete 4deb3b00563d5553ef5ae1a7839c710b 2010-06-30T03:16:43.109433Z 19 stream has-props README file 2010-07-02T05:47:28.798565Z d41d8cd98f00b204e9800998ecf8427e 2010-07-06T02:16:08.548992Z 43 spr1ng 0 build.xml file 2010-06-28T07:30:17.494569Z 0571c3a3ca6bb5ae9652bc8ba9aee7b9 2010-06-28T07:29:35.843368Z 10 spr1ng 3630 diff --git a/build/built-jar.properties b/build/built-jar.properties index 9f330d4..0f12960 100644 --- a/build/built-jar.properties +++ b/build/built-jar.properties @@ -1,4 +1,4 @@ -#Thu Jul 08 14:48:31 VLAST 2010 +#Mon Jul 12 17:57:01 VLAST 2010 /home/spr1ng/NetBeansProjects/EyeCore= /home/spr1ng/NetBeansProjects/DB4o-Server= /home/spr1ng/NetBeansProjects/Eye= diff --git a/build/classes/eye/crawler/Crawler$1.class b/build/classes/eye/crawler/Crawler$1.class index 2047864..cd404a1 100644 Binary files a/build/classes/eye/crawler/Crawler$1.class and b/build/classes/eye/crawler/Crawler$1.class differ diff --git a/build/classes/eye/crawler/Crawler$2.class b/build/classes/eye/crawler/Crawler$2.class index b233ed9..d57a7ae 100644 Binary files a/build/classes/eye/crawler/Crawler$2.class and b/build/classes/eye/crawler/Crawler$2.class differ diff --git a/build/classes/eye/crawler/Crawler.class b/build/classes/eye/crawler/Crawler.class index 1256da7..31be1e7 100644 Binary files a/build/classes/eye/crawler/Crawler.class and b/build/classes/eye/crawler/Crawler.class differ diff --git a/dist/.svn/entries b/dist/.svn/entries index f9c8fed..360b3e1 100644 --- a/dist/.svn/entries +++ b/dist/.svn/entries @@ -1,31 +1,31 @@ 10 dir -70 +93 svn://localhost/spr1ngsvn/TheEye/Eye/dist svn://localhost/spr1ngsvn/TheEye 2010-07-08T02:23:31.671869Z 55 stream 8763ed6d-9318-4032-b958-c511fcb819a9 lib dir diff --git a/dist/eye.jar b/dist/eye.jar index 122377e..b26280e 100644 Binary files a/dist/eye.jar and b/dist/eye.jar differ diff --git a/dist/lib/.svn/entries b/dist/lib/.svn/entries index 5bc0ef3..f0cdaf5 100644 --- a/dist/lib/.svn/entries +++ b/dist/lib/.svn/entries @@ -1,118 +1,118 @@ 10 dir -70 +93 svn://localhost/spr1ngsvn/TheEye/Eye/dist/lib svn://localhost/spr1ngsvn/TheEye 2010-07-08T02:23:31.671869Z 55 stream 8763ed6d-9318-4032-b958-c511fcb819a9 () DB4o-Server.jar file delete 011f0a0a6d49dbec05e0f30514541586 2010-07-08T02:23:31.671869Z 55 stream has-props db4o-7.12.145.14409-all-java5.jar file 2010-06-28T07:30:12.631071Z bd8d235631a171e277fcee08bdc9bb9f 2010-06-28T07:29:35.843368Z 10 spr1ng has-props 2445257 log4j-1.2.15.jar file 2010-06-28T07:30:12.631071Z 4d4609998fbc124ce6f0d1d48fca2614 2010-06-28T07:29:35.843368Z 10 spr1ng has-props 391834 diff --git a/dist/lib/DB4o-Server.jar b/dist/lib/DB4o-Server.jar index 2c722f5..0e6b8bd 100644 Binary files a/dist/lib/DB4o-Server.jar and b/dist/lib/DB4o-Server.jar differ diff --git a/dist/lib/EyeCore.jar b/dist/lib/EyeCore.jar index b1bc420..a1c25a5 100644 Binary files a/dist/lib/EyeCore.jar and b/dist/lib/EyeCore.jar differ diff --git a/libs/.svn/entries b/libs/.svn/entries index fbaad4d..7f3af66 100644 --- a/libs/.svn/entries +++ b/libs/.svn/entries @@ -1,96 +1,96 @@ 10 dir -70 +93 svn://localhost/spr1ngsvn/TheEye/Eye/libs svn://localhost/spr1ngsvn/TheEye 2010-06-29T03:24:59.818237Z 16 spr1ng 8763ed6d-9318-4032-b958-c511fcb819a9 db4o-7.12.145.14409-all-java5.jar file 2010-06-28T07:30:16.134571Z bd8d235631a171e277fcee08bdc9bb9f 2010-06-28T07:29:35.843368Z 10 spr1ng has-props 2445257 log4j-1.2.15.jar file 2010-06-28T07:30:16.142570Z 4d4609998fbc124ce6f0d1d48fca2614 2010-06-28T07:29:35.843368Z 10 spr1ng has-props 391834 diff --git a/nbproject/.svn/entries b/nbproject/.svn/entries index 69f1b5a..08802c1 100644 --- a/nbproject/.svn/entries +++ b/nbproject/.svn/entries @@ -1,167 +1,167 @@ 10 dir -70 +93 svn://localhost/spr1ngsvn/TheEye/Eye/nbproject svn://localhost/spr1ngsvn/TheEye -2010-07-08T03:44:15.120757Z -62 +2010-07-08T03:51:00.705642Z +72 spr1ng 8763ed6d-9318-4032-b958-c511fcb819a9 project.properties file -72 + 2010-07-08T03:48:36.035086Z 23f76663fb1dda007b4586715170bed5 2010-07-08T03:51:00.705642Z 72 spr1ng 2541 project.xml file 2010-07-08T02:38:22.910586Z b7324bf7b41ab60a31883c273b4a5245 2010-07-08T03:44:15.120757Z 62 spr1ng 1241 genfiles.properties file 2010-06-28T07:30:12.643069Z 37346fef93e45345f049998768e31a4e 2010-06-28T07:29:35.843368Z 10 spr1ng 467 private dir build-impl.xml file 2010-06-28T07:30:12.643069Z 4a5a893fc1143659600d8d906e145d72 2010-06-28T07:29:35.843368Z 10 spr1ng 43323 diff --git a/nbproject/private/.svn/entries b/nbproject/private/.svn/entries index 7ae24b6..e9e84a1 100644 --- a/nbproject/private/.svn/entries +++ b/nbproject/private/.svn/entries @@ -1,130 +1,130 @@ 10 dir -70 +93 svn://localhost/spr1ngsvn/TheEye/Eye/nbproject/private svn://localhost/spr1ngsvn/TheEye 2010-06-28T07:29:35.843368Z 10 spr1ng 8763ed6d-9318-4032-b958-c511fcb819a9 config.properties file 2010-06-28T07:30:12.643069Z d41d8cd98f00b204e9800998ecf8427e 2010-06-28T07:29:35.843368Z 10 spr1ng 0 private.properties file 2010-06-28T07:30:12.643069Z 4553f6161b521153f5e430e30fdf12f9 2010-06-28T07:29:35.843368Z 10 spr1ng 232 private.xml file 2010-06-28T07:30:12.643069Z 325a3f155f66f3ce2c7df37de2bf87c6 2010-06-28T07:29:35.843368Z 10 spr1ng 548 diff --git a/src/.svn/entries b/src/.svn/entries index 72ca04e..09de8de 100644 --- a/src/.svn/entries +++ b/src/.svn/entries @@ -1,65 +1,65 @@ 10 dir -70 +93 svn://localhost/spr1ngsvn/TheEye/Eye/src svn://localhost/spr1ngsvn/TheEye -2010-07-08T03:48:08.935715Z -70 -spr1ng +2010-07-08T05:31:17.764496Z +76 +stream 8763ed6d-9318-4032-b958-c511fcb819a9 eye dir log4j.xml file 2010-07-02T07:13:57.766566Z 7d0ca4dc1fd50bbf9008892c09c2ef8e 2010-06-28T07:29:35.843368Z 10 spr1ng 604 diff --git a/src/eye/.svn/entries b/src/eye/.svn/entries index efcd5c1..b0e8470 100644 --- a/src/eye/.svn/entries +++ b/src/eye/.svn/entries @@ -1,54 +1,54 @@ 10 dir -70 +93 svn://localhost/spr1ngsvn/TheEye/Eye/src/eye svn://localhost/spr1ngsvn/TheEye -2010-07-08T03:48:08.935715Z -70 -spr1ng +2010-07-08T05:31:17.764496Z +76 +stream 8763ed6d-9318-4032-b958-c511fcb819a9 ((conflict models dir update edited deleted (version svn://localhost/spr1ngsvn/TheEye 2 55 Eye/src/eye/models none) (version svn://localhost/spr1ngsvn/TheEye 2 69 Eye/src/eye/models dir)) (conflict net dir update edited deleted (version svn://localhost/spr1ngsvn/TheEye 2 55 Eye/src/eye/net none) (version svn://localhost/spr1ngsvn/TheEye 2 69 Eye/src/eye/net dir))) crawler dir models dir delete net dir delete diff --git a/src/eye/crawler/.svn/entries b/src/eye/crawler/.svn/entries index 7421271..ebfc157 100644 --- a/src/eye/crawler/.svn/entries +++ b/src/eye/crawler/.svn/entries @@ -1,62 +1,62 @@ 10 dir -70 +93 svn://localhost/spr1ngsvn/TheEye/Eye/src/eye/crawler svn://localhost/spr1ngsvn/TheEye -2010-07-08T03:44:15.120757Z -62 -spr1ng +2010-07-08T05:31:17.764496Z +76 +stream 8763ed6d-9318-4032-b958-c511fcb819a9 Crawler.java file -2010-07-08T03:44:15.242585Z -cfe7761a3ebfe46dfe84f2ff3f90015f -2010-07-08T03:44:15.120757Z -62 -spr1ng +2010-07-08T05:31:45.166586Z +5103f2d6548aeb5a4ba10301ad50a1df +2010-07-08T05:31:17.764496Z +76 +stream has-props -10925 +9988 diff --git a/src/eye/crawler/.svn/text-base/Crawler.java.svn-base b/src/eye/crawler/.svn/text-base/Crawler.java.svn-base index 9af3496..c2055cd 100644 --- a/src/eye/crawler/.svn/text-base/Crawler.java.svn-base +++ b/src/eye/crawler/.svn/text-base/Crawler.java.svn-base @@ -1,307 +1,292 @@ package eye.crawler; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Date; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.net.URL; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.util.HashSet; import java.util.Set; import org.apache.log4j.Logger; import com.db4o.ObjectContainer; import com.db4o.ObjectSet; import com.db4o.query.Query; import eye.core.model.Image; import eye.core.model.Place; -import eye.server.manager.impl.DBManagerBasicImpl; +import eye.server.manager.DBManagerBasicImpl; /** * The Crawler - yet another crawler ;) * @author gpdribbler, spr1ng * @version $Id$ */ public class Crawler { private static final Logger LOG = Logger.getLogger(Crawler.class); private static DBManagerBasicImpl dbm = new DBManagerBasicImpl(); public Crawler() { // setProxy("cmdeviant", 3128, "alexey", "ahGueb1e"); } public List<Place> grubPlaces(String pageSource) { List<String> regExps = new ArrayList<String>(9); regExps.add(".+js$"); regExps.add(".+xml$"); regExps.add(".+swf$"); regExps.add(".+dtd$"); regExps.add(".+jpg$"); regExps.add(".+gif$"); regExps.add(".+bmp$"); regExps.add(".+png$"); //TODO: добавить подждержку ico regExps.add(".+ico$"); List<Place> places = new ArrayList<Place>(); Set<URL> placeUrls = grubURLs(regExps, true); for (URL placeUrl : placeUrls) { places.add(new Place(placeUrl.toString())); } return places; } public List<Image> grubImages(String pageSource) { List<String> regExps = new ArrayList<String>(4); regExps.add(".+jpg$"); regExps.add(".+gif$"); regExps.add(".+bmp$"); regExps.add(".+png$"); List<Image> images = new ArrayList<Image>(); Set<URL> imageUrls = grubURLs(regExps); for (URL imageUrl : imageUrls) { images.add(new Image(imageUrl.toString())); } return images; } /** * * @param pageSource * @param regExps * @param isExcludeMode если true - url-ки, соответствующие регуляркам * не будут включены в список, иначе - будут включены только те, которые * соответствуют регуляркам * @return */ public Set<URL> grubURLs(List<String> regExps, boolean isExcludeMode) { Set<URL> urls = new HashSet<URL>(); String urlRegExp = "https?://[-_=+/,.?!&%~:|;#\\w\\d]{5,}";//PENDING String[] words = pageSource.split("\\s"); for (String word : words) { word = word.replaceFirst(".*?http", "http"); if (!word.startsWith("http")){ word = word.replaceFirst(".*?href=\"/", "http://" + domain + "/"); word = word.replaceFirst(".*?href='/", "http://" + domain + "/"); word = word.replaceFirst(".*?src=\"/", "http://" + domain + "/"); word = word.replaceFirst(".*?src='/", "http://" + domain + "/"); } String url = findRegexp(word, urlRegExp); if (url != null) { try { url = url.replaceFirst("/$", "");//убираем последний слэшик, чтобы избежать дублирования ссылок urls.add(new URL(url)); } catch (MalformedURLException ex) { LOG.error("Incorrect url: " + url, ex); } } } //Если вызван без регулярок - возвращаем все url if (regExps == null) { return urls; } for (Iterator<URL> url = urls.iterator(); url.hasNext();) { String res = findRegexp(url.next().toString(), regExps); if (isExcludeMode) { if (res != null) { url.remove(); } } else { if (res == null) { url.remove(); } } } return urls; } /** * Возвращает список всех url, найденных в исходнике страницы * @param pageSource * @return */ public Set<URL> grubURLs() { return grubURLs(null, false); } /** * Возвращает список url, найденных в исходнике страницы, соответсвующим регуляркам * @param pageSource * @return */ public Set<URL> grubURLs(List<String> regExps) { return grubURLs(regExps, false); } private static String pageSource = ""; private static String domain = ""; public void run() { ObjectContainer db = dbm.getContainer(); try { Runnable imagesGrubbing = new Runnable() { public void run() { List<Image> images = grubImages(pageSource); if (images.size() > 0) { long t1 = System.currentTimeMillis(); int savedQty = dbm.store(images); long t2 = System.currentTimeMillis() - t1; if (savedQty > 0) LOG.info("---------> Storing new images [" + savedQty + "] done. --> " + t2 + " ms"); } } }; Runnable placesGrubbing = new Runnable() { public void run() { List<Place> places = grubPlaces(pageSource); if (places.size() > 0) { long t1 = System.currentTimeMillis(); int savedQty = dbm.store(places); long t2 = System.currentTimeMillis() - t1; if (savedQty > 0) LOG.info("---------> Storing new places [" + savedQty + "] done. --> " + t2 + " ms"); } } }; Query query = db.query(); query.constrain(Place.class); query.descend("date").orderAscending();//те, что без даты сортируются наверх int placeIdx = 0; ObjectSet<Place> places = query.execute(); LOG.info("Places in db: " + places.size()); for (Place p : places) { try { placeIdx++; LOG.info("[" + placeIdx + "/" + places.size() + "] Seeking in " + p.getUrl()); //Данные для grubURL(); URL u = new URL(p.getUrl()); pageSource = getPageSource(u); domain = u.getHost(); ThreadGroup tg = new ThreadGroup("sources"); new Thread(tg, imagesGrubbing).start(); new Thread(tg, placesGrubbing).start(); //Ждем завершения потоков.. while(tg.activeCount() > 0) Thread.sleep(10); p.setDate(new Date()); db.store(p); } catch (Exception ex) { db.delete(p); LOG.error(ex); } finally { db.commit(); } } } finally { db.close(); } }//seek public static void main(String[] args) throws InterruptedException, MalformedURLException { /*if (!hasInetConnection()) { LOG.error("Inet is unreachable! =("); System.exit(1); }*/ Crawler eye = new Crawler(); -// dbm.store(new Place("http://rambler.ru")); - dbm.store(new Image("http://localhost/points1.png")); - dbm.store(new Image("http://localhost/points2.png")); - dbm.store(new Image("http://localhost/points3.png")); - dbm.store(new Image("http://localhost/points4.png")); - dbm.store(new Image("http://localhost/points5.png")); - dbm.store(new Image("http://localhost/points6.jpg")); - dbm.store(new Image("http://localhost/points7.jpg")); - dbm.store(new Image("http://localhost/points8.jpg")); - dbm.store(new Image("http://localhost/medved1.jpg")); - dbm.store(new Image("http://localhost/medved2.jpg")); - dbm.store(new Image("http://localhost/medved3.jpg")); - dbm.store(new Image("http://localhost/medved4.jpg")); - dbm.store(new Image("http://localhost/medved5.jpg")); - dbm.store(new Image("http://localhost/logo.png")); - dbm.store(new Image("http://localhost/logo2.png")); + dbm.store(new Place("http://rambler.ru")); // eye.watchDb(); // eye.run(); - /* while (true) { + while (true) { eye.run(); Thread.sleep(1000); - }*/ + } /*URL u = new URL("http://ya.ru"); pageSource = eye.getPageSource(u); domain = u.getHost(); Set<URL> urls = eye.grubURLs(); for (URL url : urls) { System.out.println(url); } System.out.println("size: " + urls.size());*/ } /** * Находит фрагмент строки из source, соответстующий любой регулярке из regs * @param source * @param regs * @return */ private String findRegexp(String source, List<String> regs) { for (String reg : regs) { Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(source.toLowerCase()); if (matcher.find()) { return matcher.group(); } } return null; } /** * Находит фрагмент строки из source, соответстующий регулярке из reg * @param source * @param reg * @return */ private String findRegexp(String source, String reg) { List<String> regs = new ArrayList<String>(1); regs.add(reg); return findRegexp(source, regs); } private String getPageSource(URL url) { StringBuilder response = new StringBuilder(); HttpURLConnection con; try { con = (HttpURLConnection) url.openConnection(); // con.setRequestProperty("Accept-Charset", "cp1251"); con.connect(); Scanner scanner = new Scanner(con.getInputStream()); while (scanner.hasNext()) { response.append(scanner.nextLine()); } con.disconnect(); } catch (Exception ex) { LOG.error("The place is unreachable: " + url); return ""; } return response.toString(); } } diff --git a/src/eye/crawler/Crawler.java b/src/eye/crawler/Crawler.java index fcd2f5a..1fc4fd9 100644 --- a/src/eye/crawler/Crawler.java +++ b/src/eye/crawler/Crawler.java @@ -1,307 +1,302 @@ package eye.crawler; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Date; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.net.URL; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.util.HashSet; import java.util.Set; import org.apache.log4j.Logger; import com.db4o.ObjectContainer; import com.db4o.ObjectSet; import com.db4o.query.Query; import eye.core.model.Image; import eye.core.model.Place; -import eye.server.manager.impl.DBManagerBasicImpl; +import eye.core.util.InetUtils; +import eye.server.manager.DBManagerBasicImpl; /** * The Crawler - yet another crawler ;) * @author gpdribbler, spr1ng - * @version $Id: Crawler.java 62 2010-07-08 03:44:15Z spr1ng $ + * @version $Id: Crawler.java 76 2010-07-08 05:31:17Z stream $ */ public class Crawler { private static final Logger LOG = Logger.getLogger(Crawler.class); private static DBManagerBasicImpl dbm = new DBManagerBasicImpl(); public Crawler() { // setProxy("cmdeviant", 3128, "alexey", "ahGueb1e"); } public List<Place> grubPlaces(String pageSource) { List<String> regExps = new ArrayList<String>(9); regExps.add(".+js$"); regExps.add(".+xml$"); regExps.add(".+swf$"); regExps.add(".+dtd$"); regExps.add(".+jpg$"); regExps.add(".+gif$"); regExps.add(".+bmp$"); regExps.add(".+png$"); //TODO: добавить подждержку ico regExps.add(".+ico$"); List<Place> places = new ArrayList<Place>(); Set<URL> placeUrls = grubURLs(regExps, true); for (URL placeUrl : placeUrls) { places.add(new Place(placeUrl.toString())); } return places; } public List<Image> grubImages(String pageSource) { List<String> regExps = new ArrayList<String>(4); regExps.add(".+jpg$"); regExps.add(".+gif$"); regExps.add(".+bmp$"); regExps.add(".+png$"); List<Image> images = new ArrayList<Image>(); Set<URL> imageUrls = grubURLs(regExps); for (URL imageUrl : imageUrls) { images.add(new Image(imageUrl.toString())); } return images; } /** * * @param pageSource * @param regExps * @param isExcludeMode если true - url-ки, соответствующие регуляркам * не будут включены в список, иначе - будут включены только те, которые * соответствуют регуляркам * @return */ public Set<URL> grubURLs(List<String> regExps, boolean isExcludeMode) { Set<URL> urls = new HashSet<URL>(); String urlRegExp = "https?://[-_=+/,.?!&%~:|;#\\w\\d]{5,}";//PENDING String[] words = pageSource.split("\\s"); for (String word : words) { word = word.replaceFirst(".*?http", "http"); if (!word.startsWith("http")){ word = word.replaceFirst(".*?href=\"/", "http://" + domain + "/"); word = word.replaceFirst(".*?href='/", "http://" + domain + "/"); word = word.replaceFirst(".*?src=\"/", "http://" + domain + "/"); word = word.replaceFirst(".*?src='/", "http://" + domain + "/"); } String url = findRegexp(word, urlRegExp); if (url != null) { try { url = url.replaceFirst("/$", "");//убираем последний слэшик, чтобы избежать дублирования ссылок urls.add(new URL(url)); } catch (MalformedURLException ex) { LOG.error("Incorrect url: " + url, ex); } } } //Если вызван без регулярок - возвращаем все url if (regExps == null) { return urls; } for (Iterator<URL> url = urls.iterator(); url.hasNext();) { String res = findRegexp(url.next().toString(), regExps); if (isExcludeMode) { if (res != null) { url.remove(); } } else { if (res == null) { url.remove(); } } } return urls; } /** * Возвращает список всех url, найденных в исходнике страницы * @param pageSource * @return */ public Set<URL> grubURLs() { return grubURLs(null, false); } /** * Возвращает список url, найденных в исходнике страницы, соответсвующим регуляркам * @param pageSource * @return */ public Set<URL> grubURLs(List<String> regExps) { return grubURLs(regExps, false); } private static String pageSource = ""; private static String domain = ""; public void run() { ObjectContainer db = dbm.getContainer(); try { Runnable imagesGrubbing = new Runnable() { public void run() { List<Image> images = grubImages(pageSource); if (images.size() > 0) { long t1 = System.currentTimeMillis(); int savedQty = dbm.store(images); long t2 = System.currentTimeMillis() - t1; if (savedQty > 0) LOG.info("---------> Storing new images [" + savedQty + "] done. --> " + t2 + " ms"); } } }; Runnable placesGrubbing = new Runnable() { public void run() { List<Place> places = grubPlaces(pageSource); if (places.size() > 0) { long t1 = System.currentTimeMillis(); int savedQty = dbm.store(places); long t2 = System.currentTimeMillis() - t1; if (savedQty > 0) LOG.info("---------> Storing new places [" + savedQty + "] done. --> " + t2 + " ms"); } } }; Query query = db.query(); query.constrain(Place.class); query.descend("date").orderAscending();//те, что без даты сортируются наверх int placeIdx = 0; ObjectSet<Place> places = query.execute(); LOG.info("Places in db: " + places.size()); for (Place p : places) { try { placeIdx++; LOG.info("[" + placeIdx + "/" + places.size() + "] Seeking in " + p.getUrl()); //Данные для grubURL(); URL u = new URL(p.getUrl()); pageSource = getPageSource(u); domain = u.getHost(); ThreadGroup tg = new ThreadGroup("sources"); new Thread(tg, imagesGrubbing).start(); new Thread(tg, placesGrubbing).start(); //Ждем завершения потоков.. while(tg.activeCount() > 0) Thread.sleep(10); p.setDate(new Date()); db.store(p); } catch (Exception ex) { db.delete(p); LOG.error(ex); } finally { db.commit(); } } } finally { db.close(); } }//seek public static void main(String[] args) throws InterruptedException, MalformedURLException { - /*if (!hasInetConnection()) { + if (!InetUtils.hasInetConnection()) { LOG.error("Inet is unreachable! =("); System.exit(1); - }*/ + } Crawler eye = new Crawler(); -// dbm.store(new Place("http://rambler.ru")); - dbm.store(new Image("http://localhost/points1.png")); - dbm.store(new Image("http://localhost/points2.png")); - dbm.store(new Image("http://localhost/points3.png")); - dbm.store(new Image("http://localhost/points4.png")); - dbm.store(new Image("http://localhost/points5.png")); - dbm.store(new Image("http://localhost/points6.jpg")); - dbm.store(new Image("http://localhost/points7.jpg")); - dbm.store(new Image("http://localhost/points8.jpg")); - dbm.store(new Image("http://localhost/medved1.jpg")); - dbm.store(new Image("http://localhost/medved2.jpg")); - dbm.store(new Image("http://localhost/medved3.jpg")); - dbm.store(new Image("http://localhost/medved4.jpg")); - dbm.store(new Image("http://localhost/medved5.jpg")); - dbm.store(new Image("http://localhost/logo.png")); - dbm.store(new Image("http://localhost/logo2.png")); +// dbm.store(new Place("http://wallpapers-best.ru")); +// dbm.store(new Place("http://gee.ru")); + for (int i = 1; i <= 9; i++) { + dbm.store(new Image("http://localhost/points" + i + ".jpg")); + dbm.store(new Image("http://localhost/points" + i + ".png")); + dbm.store(new Image("http://localhost/medved" + i + ".jpg")); + dbm.store(new Image("http://localhost/medved" + i + ".png")); + dbm.store(new Image("http://localhost/logo.png")); + } + // eye.watchDb(); // eye.run(); - /* while (true) { + /*while (true) { eye.run(); Thread.sleep(1000); }*/ /*URL u = new URL("http://ya.ru"); pageSource = eye.getPageSource(u); domain = u.getHost(); Set<URL> urls = eye.grubURLs(); for (URL url : urls) { System.out.println(url); } System.out.println("size: " + urls.size());*/ } /** * Находит фрагмент строки из source, соответстующий любой регулярке из regs * @param source * @param regs * @return */ private String findRegexp(String source, List<String> regs) { for (String reg : regs) { Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(source.toLowerCase()); if (matcher.find()) { return matcher.group(); } } return null; } /** * Находит фрагмент строки из source, соответстующий регулярке из reg * @param source * @param reg * @return */ private String findRegexp(String source, String reg) { List<String> regs = new ArrayList<String>(1); regs.add(reg); return findRegexp(source, regs); } private String getPageSource(URL url) { StringBuilder response = new StringBuilder(); HttpURLConnection con; try { con = (HttpURLConnection) url.openConnection(); // con.setRequestProperty("Accept-Charset", "cp1251"); con.connect(); Scanner scanner = new Scanner(con.getInputStream()); while (scanner.hasNext()) { response.append(scanner.nextLine()); } con.disconnect(); } catch (Exception ex) { LOG.error("The place is unreachable: " + url); return ""; } return response.toString(); } }
spr1ng/Crawler
c66ec407bfb43cf49a20583cb5d9b20efab20681
Небольшой рефакторинг ;)
diff --git a/.svn/dir-prop-base b/.svn/dir-prop-base index bd19930..c67a1b9 100644 --- a/.svn/dir-prop-base +++ b/.svn/dir-prop-base @@ -1,6 +1,7 @@ K 10 svn:ignore -V 6 +V 11 build +.git END diff --git a/.svn/entries b/.svn/entries index 405bc65..901263d 100644 --- a/.svn/entries +++ b/.svn/entries @@ -1,133 +1,164 @@ 10 dir -19 +70 svn://localhost/spr1ngsvn/TheEye/Eye svn://localhost/spr1ngsvn/TheEye -2010-06-30T03:16:43.109433Z -19 -stream +2010-07-08T03:48:08.935715Z +70 +spr1ng has-props 8763ed6d-9318-4032-b958-c511fcb819a9 () -.git -dir - dist dir nbproject dir src dir manifest.mf file 2010-06-28T07:30:17.494569Z d6fe4af2f67849f1c01635b0ed4c443d 2010-06-28T07:29:35.843368Z 10 spr1ng 82 libs dir db.db4o file delete 4deb3b00563d5553ef5ae1a7839c710b 2010-06-30T03:16:43.109433Z 19 stream has-props +README +file + + + + +2010-07-02T05:47:28.798565Z +d41d8cd98f00b204e9800998ecf8427e +2010-07-06T02:16:08.548992Z +43 +spr1ng + + + + + + + + + + + + + + + + + + + + + +0 + build.xml file 2010-06-28T07:30:17.494569Z 0571c3a3ca6bb5ae9652bc8ba9aee7b9 2010-06-28T07:29:35.843368Z 10 spr1ng 3630 diff --git a/.svn/text-base/README.svn-base b/.svn/text-base/README.svn-base new file mode 100644 index 0000000..e69de29 diff --git a/build/built-jar.properties b/build/built-jar.properties new file mode 100644 index 0000000..9f330d4 --- /dev/null +++ b/build/built-jar.properties @@ -0,0 +1,4 @@ +#Thu Jul 08 14:48:31 VLAST 2010 +/home/spr1ng/NetBeansProjects/EyeCore= +/home/spr1ng/NetBeansProjects/DB4o-Server= +/home/spr1ng/NetBeansProjects/Eye= diff --git a/build/classes/eye/DBManagerEyeImpl.class b/build/classes/eye/DBManagerEyeImpl.class deleted file mode 100644 index 18e7927..0000000 Binary files a/build/classes/eye/DBManagerEyeImpl.class and /dev/null differ diff --git a/build/classes/eye/Eye$1.class b/build/classes/eye/Eye$1.class deleted file mode 100644 index 9af2b0e..0000000 Binary files a/build/classes/eye/Eye$1.class and /dev/null differ diff --git a/build/classes/eye/Eye$2.class b/build/classes/eye/Eye$2.class deleted file mode 100644 index 0efdf79..0000000 Binary files a/build/classes/eye/Eye$2.class and /dev/null differ diff --git a/build/classes/eye/Eye.class b/build/classes/eye/Eye.class deleted file mode 100644 index 17fe401..0000000 Binary files a/build/classes/eye/Eye.class and /dev/null differ diff --git a/build/classes/eye/IIException.class b/build/classes/eye/IIException.class deleted file mode 100644 index 3a6dbc0..0000000 Binary files a/build/classes/eye/IIException.class and /dev/null differ diff --git a/build/classes/eye/ImageFactory.class b/build/classes/eye/ImageFactory.class deleted file mode 100644 index e3c66c4..0000000 Binary files a/build/classes/eye/ImageFactory.class and /dev/null differ diff --git a/build/classes/eye/crawler/Crawler$1.class b/build/classes/eye/crawler/Crawler$1.class new file mode 100644 index 0000000..2047864 Binary files /dev/null and b/build/classes/eye/crawler/Crawler$1.class differ diff --git a/build/classes/eye/crawler/Crawler$2.class b/build/classes/eye/crawler/Crawler$2.class new file mode 100644 index 0000000..b233ed9 Binary files /dev/null and b/build/classes/eye/crawler/Crawler$2.class differ diff --git a/build/classes/eye/crawler/Crawler.class b/build/classes/eye/crawler/Crawler.class new file mode 100644 index 0000000..1256da7 Binary files /dev/null and b/build/classes/eye/crawler/Crawler.class differ diff --git a/build/classes/eye/models/Image.class b/build/classes/eye/models/Image.class deleted file mode 100644 index b2253fc..0000000 Binary files a/build/classes/eye/models/Image.class and /dev/null differ diff --git a/build/classes/eye/models/Place.class b/build/classes/eye/models/Place.class deleted file mode 100644 index bccdeed..0000000 Binary files a/build/classes/eye/models/Place.class and /dev/null differ diff --git a/build/classes/eye/models/Point.class b/build/classes/eye/models/Point.class deleted file mode 100644 index d2135a2..0000000 Binary files a/build/classes/eye/models/Point.class and /dev/null differ diff --git a/build/classes/eye/models/RemoteSource.class b/build/classes/eye/models/RemoteSource.class deleted file mode 100644 index 12f3cdd..0000000 Binary files a/build/classes/eye/models/RemoteSource.class and /dev/null differ diff --git a/build/classes/eye/net/InetUtils$1.class b/build/classes/eye/net/InetUtils$1.class deleted file mode 100644 index 0477528..0000000 Binary files a/build/classes/eye/net/InetUtils$1.class and /dev/null differ diff --git a/build/classes/eye/net/InetUtils.class b/build/classes/eye/net/InetUtils.class deleted file mode 100644 index 6acae90..0000000 Binary files a/build/classes/eye/net/InetUtils.class and /dev/null differ diff --git a/dist/.svn/entries b/dist/.svn/entries index 7ea885c..f9c8fed 100644 --- a/dist/.svn/entries +++ b/dist/.svn/entries @@ -1,65 +1,31 @@ 10 dir -19 +70 svn://localhost/spr1ngsvn/TheEye/Eye/dist svn://localhost/spr1ngsvn/TheEye -2010-06-30T03:16:43.109433Z -19 +2010-07-08T02:23:31.671869Z +55 stream 8763ed6d-9318-4032-b958-c511fcb819a9 lib dir -eye.jar -file -28 - - - -2010-07-01T05:27:54.362573Z -85d087ca1a76141ad806519995e4127a -2010-07-01T05:35:24.601857Z -28 -spr1ng -has-props - - - - - - - - - - - - - - - - - - - - -34123 - diff --git a/dist/.svn/prop-base/eye.jar.svn-base b/dist/.svn/prop-base/eye.jar.svn-base deleted file mode 100644 index 5e9587e..0000000 --- a/dist/.svn/prop-base/eye.jar.svn-base +++ /dev/null @@ -1,5 +0,0 @@ -K 13 -svn:mime-type -V 24 -application/octet-stream -END diff --git a/dist/.svn/text-base/eye.jar.svn-base b/dist/.svn/text-base/eye.jar.svn-base deleted file mode 100644 index c813263..0000000 Binary files a/dist/.svn/text-base/eye.jar.svn-base and /dev/null differ diff --git a/dist/eye.jar b/dist/eye.jar index c813263..122377e 100644 Binary files a/dist/eye.jar and b/dist/eye.jar differ diff --git a/dist/lib/.svn/entries b/dist/lib/.svn/entries index 5a9c75f..5bc0ef3 100644 --- a/dist/lib/.svn/entries +++ b/dist/lib/.svn/entries @@ -1,118 +1,118 @@ 10 dir -19 +70 svn://localhost/spr1ngsvn/TheEye/Eye/dist/lib svn://localhost/spr1ngsvn/TheEye -2010-06-30T03:16:43.109433Z -19 +2010-07-08T02:23:31.671869Z +55 stream 8763ed6d-9318-4032-b958-c511fcb819a9 () DB4o-Server.jar file delete -9e6b965bbbf187fde81863631a7bc86c -2010-06-30T03:16:43.109433Z -19 +011f0a0a6d49dbec05e0f30514541586 +2010-07-08T02:23:31.671869Z +55 stream has-props db4o-7.12.145.14409-all-java5.jar file 2010-06-28T07:30:12.631071Z bd8d235631a171e277fcee08bdc9bb9f 2010-06-28T07:29:35.843368Z 10 spr1ng has-props 2445257 log4j-1.2.15.jar file 2010-06-28T07:30:12.631071Z 4d4609998fbc124ce6f0d1d48fca2614 2010-06-28T07:29:35.843368Z 10 spr1ng has-props 391834 diff --git a/dist/lib/.svn/text-base/DB4o-Server.jar.svn-base b/dist/lib/.svn/text-base/DB4o-Server.jar.svn-base index fd0b5bd..63547d5 100644 Binary files a/dist/lib/.svn/text-base/DB4o-Server.jar.svn-base and b/dist/lib/.svn/text-base/DB4o-Server.jar.svn-base differ diff --git a/dist/lib/DB4o-Server.jar b/dist/lib/DB4o-Server.jar index 7a2a7cc..2c722f5 100644 Binary files a/dist/lib/DB4o-Server.jar and b/dist/lib/DB4o-Server.jar differ diff --git a/dist/lib/EyeCore.jar b/dist/lib/EyeCore.jar new file mode 100644 index 0000000..b1bc420 Binary files /dev/null and b/dist/lib/EyeCore.jar differ diff --git a/libs/.svn/entries b/libs/.svn/entries index ba5619f..fbaad4d 100644 --- a/libs/.svn/entries +++ b/libs/.svn/entries @@ -1,96 +1,96 @@ 10 dir -19 +70 svn://localhost/spr1ngsvn/TheEye/Eye/libs svn://localhost/spr1ngsvn/TheEye 2010-06-29T03:24:59.818237Z 16 spr1ng 8763ed6d-9318-4032-b958-c511fcb819a9 db4o-7.12.145.14409-all-java5.jar file 2010-06-28T07:30:16.134571Z bd8d235631a171e277fcee08bdc9bb9f 2010-06-28T07:29:35.843368Z 10 spr1ng has-props 2445257 log4j-1.2.15.jar file 2010-06-28T07:30:16.142570Z 4d4609998fbc124ce6f0d1d48fca2614 2010-06-28T07:29:35.843368Z 10 spr1ng has-props 391834 diff --git a/nbproject/.svn/entries b/nbproject/.svn/entries index c9edbcf..69f1b5a 100644 --- a/nbproject/.svn/entries +++ b/nbproject/.svn/entries @@ -1,167 +1,167 @@ 10 dir -19 +70 svn://localhost/spr1ngsvn/TheEye/Eye/nbproject svn://localhost/spr1ngsvn/TheEye -2010-06-28T07:29:35.843368Z -10 +2010-07-08T03:44:15.120757Z +62 spr1ng 8763ed6d-9318-4032-b958-c511fcb819a9 project.properties file +72 - -2010-06-28T07:30:12.643069Z -6f695dff7cd7ee233355fec38134470b -2010-06-28T07:29:35.843368Z -10 +2010-07-08T03:48:36.035086Z +23f76663fb1dda007b4586715170bed5 +2010-07-08T03:51:00.705642Z +72 spr1ng -2428 +2541 project.xml file -2010-06-28T07:30:12.643069Z -ac54815196fe952c7a6edcec31fd9a53 -2010-06-28T07:29:35.843368Z -10 +2010-07-08T02:38:22.910586Z +b7324bf7b41ab60a31883c273b4a5245 +2010-07-08T03:44:15.120757Z +62 spr1ng -922 +1241 genfiles.properties file 2010-06-28T07:30:12.643069Z 37346fef93e45345f049998768e31a4e 2010-06-28T07:29:35.843368Z 10 spr1ng 467 private dir build-impl.xml file 2010-06-28T07:30:12.643069Z 4a5a893fc1143659600d8d906e145d72 2010-06-28T07:29:35.843368Z 10 spr1ng 43323 diff --git a/nbproject/.svn/text-base/genfiles.properties.netbeans-base b/nbproject/.svn/text-base/genfiles.properties.netbeans-base new file mode 100644 index 0000000..b1f8948 --- /dev/null +++ b/nbproject/.svn/text-base/genfiles.properties.netbeans-base @@ -0,0 +1,8 @@ +build.xml.data.CRC32=c7637cc6 +build.xml.script.CRC32=809b2dff [email protected] +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=c7637cc6 +nbproject/build-impl.xml.script.CRC32=040939fe +nbproject/[email protected] diff --git a/nbproject/.svn/text-base/project.properties.netbeans-base b/nbproject/.svn/text-base/project.properties.netbeans-base new file mode 100644 index 0000000..2b08b75 --- /dev/null +++ b/nbproject/.svn/text-base/project.properties.netbeans-base @@ -0,0 +1,73 @@ +application.title=eye +application.vendor=Admin +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +build.generated.sources.dir=${build.dir}/generated-sources +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +# Uncomment to specify the preferred debugger connection transport: +#debug.transport=dt_socket +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/eye.jar +dist.javadoc.dir=${dist.dir}/javadoc +endorsed.classpath= +excludes= +file.reference.db4o-7.12.145.14409-all-java5.jar=../DB4o-Server/libs/db4o-7.12.145.14409-all-java5.jar +file.reference.log4j-1.2.15.jar=libs\\log4j-1.2.15.jar +includes=** +jar.compress=false +javac.classpath=\ + ${reference.DB4o-Server.jar}:\ + ${file.reference.log4j-1.2.15.jar}:\ + ${file.reference.db4o-7.12.145.14409-all-java5.jar} +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.source=1.5 +javac.target=1.5 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir}:\ + ${libs.junit.classpath}:\ + ${libs.junit_4.classpath} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding=${source.encoding} +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +jaxbwiz.endorsed.dirs="${netbeans.home}/../ide12/modules/ext/jaxb/api" +main.class=eye.Eye +manifest.file=manifest.mf +meta.inf.dir=${src.dir}/META-INF +platform.active=default_platform +project.DB4o-Server=../DB4o-Server +reference.DB4o-Server.jar=${project.DB4o-Server}/dist/DB4o-Server.jar +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value +# or test-sys-prop.name=value to set system properties for unit tests): +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +source.encoding=UTF-8 +src.dir=src +test.src.dir=test diff --git a/nbproject/.svn/text-base/project.properties.svn-base b/nbproject/.svn/text-base/project.properties.svn-base index 2b08b75..4e866c4 100644 --- a/nbproject/.svn/text-base/project.properties.svn-base +++ b/nbproject/.svn/text-base/project.properties.svn-base @@ -1,73 +1,76 @@ application.title=eye application.vendor=Admin build.classes.dir=${build.dir}/classes build.classes.excludes=**/*.java,**/*.form # This directory is removed when the project is cleaned: build.dir=build build.generated.dir=${build.dir}/generated build.generated.sources.dir=${build.dir}/generated-sources # Only compile against the classpath explicitly listed here: build.sysclasspath=ignore build.test.classes.dir=${build.dir}/test/classes build.test.results.dir=${build.dir}/test/results # Uncomment to specify the preferred debugger connection transport: #debug.transport=dt_socket debug.classpath=\ ${run.classpath} debug.test.classpath=\ ${run.test.classpath} # This directory is removed when the project is cleaned: dist.dir=dist dist.jar=${dist.dir}/eye.jar dist.javadoc.dir=${dist.dir}/javadoc endorsed.classpath= excludes= -file.reference.db4o-7.12.145.14409-all-java5.jar=../DB4o-Server/libs/db4o-7.12.145.14409-all-java5.jar +file.reference.db4o-7.12.145.14409-all-java5.jar=libs/db4o-7.12.145.14409-all-java5.jar file.reference.log4j-1.2.15.jar=libs\\log4j-1.2.15.jar includes=** jar.compress=false javac.classpath=\ ${reference.DB4o-Server.jar}:\ + ${reference.EyeCore.jar}:\ ${file.reference.log4j-1.2.15.jar}:\ ${file.reference.db4o-7.12.145.14409-all-java5.jar} # Space-separated list of extra javac options javac.compilerargs= javac.deprecation=false javac.source=1.5 javac.target=1.5 javac.test.classpath=\ ${javac.classpath}:\ ${build.classes.dir}:\ ${libs.junit.classpath}:\ ${libs.junit_4.classpath} javadoc.additionalparam= javadoc.author=false javadoc.encoding=${source.encoding} javadoc.noindex=false javadoc.nonavbar=false javadoc.notree=false javadoc.private=false javadoc.splitindex=true javadoc.use=true javadoc.version=false javadoc.windowtitle= jaxbwiz.endorsed.dirs="${netbeans.home}/../ide12/modules/ext/jaxb/api" -main.class=eye.Eye +main.class=eye.crawler.Crawler manifest.file=manifest.mf meta.inf.dir=${src.dir}/META-INF platform.active=default_platform project.DB4o-Server=../DB4o-Server +project.EyeCore=../EyeCore reference.DB4o-Server.jar=${project.DB4o-Server}/dist/DB4o-Server.jar +reference.EyeCore.jar=${project.EyeCore}/dist/EyeCore.jar run.classpath=\ ${javac.classpath}:\ ${build.classes.dir} # Space-separated list of JVM arguments used when running the project # (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value # or test-sys-prop.name=value to set system properties for unit tests): run.jvmargs= run.test.classpath=\ ${javac.test.classpath}:\ ${build.test.classes.dir} source.encoding=UTF-8 src.dir=src test.src.dir=test diff --git a/nbproject/.svn/text-base/project.xml.netbeans-base b/nbproject/.svn/text-base/project.xml.netbeans-base new file mode 100644 index 0000000..24b7095 --- /dev/null +++ b/nbproject/.svn/text-base/project.xml.netbeans-base @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://www.netbeans.org/ns/project/1"> + <type>org.netbeans.modules.java.j2seproject</type> + <configuration> + <data xmlns="http://www.netbeans.org/ns/j2se-project/3"> + <name>eye</name> + <source-roots> + <root id="src.dir"/> + </source-roots> + <test-roots> + <root id="test.src.dir"/> + </test-roots> + </data> + <references xmlns="http://www.netbeans.org/ns/ant-project-references/1"> + <reference> + <foreign-project>DB4o-Server</foreign-project> + <artifact-type>jar</artifact-type> + <script>build.xml</script> + <target>jar</target> + <clean-target>clean</clean-target> + <id>jar</id> + </reference> + </references> + </configuration> +</project> diff --git a/nbproject/.svn/text-base/project.xml.svn-base b/nbproject/.svn/text-base/project.xml.svn-base index 24b7095..99af66c 100644 --- a/nbproject/.svn/text-base/project.xml.svn-base +++ b/nbproject/.svn/text-base/project.xml.svn-base @@ -1,25 +1,33 @@ <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://www.netbeans.org/ns/project/1"> <type>org.netbeans.modules.java.j2seproject</type> <configuration> <data xmlns="http://www.netbeans.org/ns/j2se-project/3"> <name>eye</name> <source-roots> <root id="src.dir"/> </source-roots> <test-roots> <root id="test.src.dir"/> </test-roots> </data> <references xmlns="http://www.netbeans.org/ns/ant-project-references/1"> <reference> <foreign-project>DB4o-Server</foreign-project> <artifact-type>jar</artifact-type> <script>build.xml</script> <target>jar</target> <clean-target>clean</clean-target> <id>jar</id> </reference> + <reference> + <foreign-project>EyeCore</foreign-project> + <artifact-type>jar</artifact-type> + <script>build.xml</script> + <target>jar</target> + <clean-target>clean</clean-target> + <id>jar</id> + </reference> </references> </configuration> </project> diff --git a/nbproject/build-impl.xml b/nbproject/build-impl.xml index e5f30a8..1a2fefe 100644 --- a/nbproject/build-impl.xml +++ b/nbproject/build-impl.xml @@ -1,819 +1,833 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- *** GENERATED FROM project.xml - DO NOT EDIT *** *** EDIT ../build.xml INSTEAD *** For the purpose of easier reading the script is divided into following sections: - initialization - compilation - jar - execution - debugging - javadoc - junit compilation - junit execution - junit debugging - applet - cleanup --> <project xmlns:j2seproject1="http://www.netbeans.org/ns/j2se-project/1" xmlns:j2seproject3="http://www.netbeans.org/ns/j2se-project/3" xmlns:jaxrpc="http://www.netbeans.org/ns/j2se-project/jax-rpc" basedir=".." default="default" name="eye-impl"> <fail message="Please build using Ant 1.7.1 or higher."> <condition> <not> <antversion atleast="1.7.1"/> </not> </condition> </fail> <target depends="test,jar,javadoc" description="Build and test whole project." name="default"/> <!-- ====================== INITIALIZATION SECTION ====================== --> <target name="-pre-init"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> </target> <target depends="-pre-init" name="-init-private"> <property file="nbproject/private/config.properties"/> <property file="nbproject/private/configs/${config}.properties"/> <property file="nbproject/private/private.properties"/> </target> <target depends="-pre-init,-init-private" name="-init-user"> <property file="${user.properties.file}"/> <!-- The two properties below are usually overridden --> <!-- by the active platform. Just a fallback. --> <property name="default.javac.source" value="1.4"/> <property name="default.javac.target" value="1.4"/> </target> <target depends="-pre-init,-init-private,-init-user" name="-init-project"> <property file="nbproject/configs/${config}.properties"/> <property file="nbproject/project.properties"/> </target> <target depends="-pre-init,-init-private,-init-user,-init-project,-init-macrodef-property" name="-do-init"> <available file="${manifest.file}" property="manifest.available"/> <condition property="main.class.available"> <and> <isset property="main.class"/> <not> <equals arg1="${main.class}" arg2="" trim="true"/> </not> </and> </condition> <condition property="manifest.available+main.class"> <and> <isset property="manifest.available"/> <isset property="main.class.available"/> </and> </condition> <condition property="do.mkdist"> <and> <isset property="libs.CopyLibs.classpath"/> <not> <istrue value="${mkdist.disabled}"/> </not> </and> </condition> <condition property="manifest.available+main.class+mkdist.available"> <and> <istrue value="${manifest.available+main.class}"/> <isset property="do.mkdist"/> </and> </condition> <condition property="manifest.available+mkdist.available"> <and> <istrue value="${manifest.available}"/> <isset property="do.mkdist"/> </and> </condition> <condition property="manifest.available-mkdist.available"> <or> <istrue value="${manifest.available}"/> <isset property="do.mkdist"/> </or> </condition> <condition property="manifest.available+main.class-mkdist.available"> <or> <istrue value="${manifest.available+main.class}"/> <isset property="do.mkdist"/> </or> </condition> <condition property="have.tests"> <or> <available file="${test.src.dir}"/> </or> </condition> <condition property="have.sources"> <or> <available file="${src.dir}"/> </or> </condition> <condition property="netbeans.home+have.tests"> <and> <isset property="netbeans.home"/> <isset property="have.tests"/> </and> </condition> <condition property="no.javadoc.preview"> <and> <isset property="javadoc.preview"/> <isfalse value="${javadoc.preview}"/> </and> </condition> <property name="run.jvmargs" value=""/> <property name="javac.compilerargs" value=""/> <property name="work.dir" value="${basedir}"/> <condition property="no.deps"> <and> <istrue value="${no.dependencies}"/> </and> </condition> <property name="javac.debug" value="true"/> <property name="javadoc.preview" value="true"/> <property name="application.args" value=""/> <property name="source.encoding" value="${file.encoding}"/> <property name="runtime.encoding" value="${source.encoding}"/> <condition property="javadoc.encoding.used" value="${javadoc.encoding}"> <and> <isset property="javadoc.encoding"/> <not> <equals arg1="${javadoc.encoding}" arg2=""/> </not> </and> </condition> <property name="javadoc.encoding.used" value="${source.encoding}"/> <property name="includes" value="**"/> <property name="excludes" value=""/> <property name="do.depend" value="false"/> <condition property="do.depend.true"> <istrue value="${do.depend}"/> </condition> <path id="endorsed.classpath.path" path="${endorsed.classpath}"/> <condition else="" property="endorsed.classpath.cmd.line.arg" value="-Xbootclasspath/p:'${toString:endorsed.classpath.path}'"> <length length="0" string="${endorsed.classpath}" when="greater"/> </condition> <property name="javac.fork" value="false"/> </target> <target name="-post-init"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> </target> <target depends="-pre-init,-init-private,-init-user,-init-project,-do-init" name="-init-check"> <fail unless="src.dir">Must set src.dir</fail> <fail unless="test.src.dir">Must set test.src.dir</fail> <fail unless="build.dir">Must set build.dir</fail> <fail unless="dist.dir">Must set dist.dir</fail> <fail unless="build.classes.dir">Must set build.classes.dir</fail> <fail unless="dist.javadoc.dir">Must set dist.javadoc.dir</fail> <fail unless="build.test.classes.dir">Must set build.test.classes.dir</fail> <fail unless="build.test.results.dir">Must set build.test.results.dir</fail> <fail unless="build.classes.excludes">Must set build.classes.excludes</fail> <fail unless="dist.jar">Must set dist.jar</fail> </target> <target name="-init-macrodef-property"> <macrodef name="property" uri="http://www.netbeans.org/ns/j2se-project/1"> <attribute name="name"/> <attribute name="value"/> <sequential> <property name="@{name}" value="${@{value}}"/> </sequential> </macrodef> </target> <target name="-init-macrodef-javac"> <macrodef name="javac" uri="http://www.netbeans.org/ns/j2se-project/3"> <attribute default="${src.dir}" name="srcdir"/> <attribute default="${build.classes.dir}" name="destdir"/> <attribute default="${javac.classpath}" name="classpath"/> <attribute default="${includes}" name="includes"/> <attribute default="${excludes}" name="excludes"/> <attribute default="${javac.debug}" name="debug"/> <attribute default="${empty.dir}" name="sourcepath"/> <attribute default="${empty.dir}" name="gensrcdir"/> <element name="customize" optional="true"/> <sequential> <property location="${build.dir}/empty" name="empty.dir"/> <mkdir dir="${empty.dir}"/> <javac debug="@{debug}" deprecation="${javac.deprecation}" destdir="@{destdir}" encoding="${source.encoding}" excludes="@{excludes}" fork="${javac.fork}" includeantruntime="false" includes="@{includes}" source="${javac.source}" sourcepath="@{sourcepath}" srcdir="@{srcdir}" target="${javac.target}" tempdir="${java.io.tmpdir}"> <src> <dirset dir="@{gensrcdir}" erroronmissingdir="false"> <include name="*"/> </dirset> </src> <classpath> <path path="@{classpath}"/> </classpath> <compilerarg line="${endorsed.classpath.cmd.line.arg}"/> <compilerarg line="${javac.compilerargs}"/> <customize/> </javac> </sequential> </macrodef> <macrodef name="depend" uri="http://www.netbeans.org/ns/j2se-project/3"> <attribute default="${src.dir}" name="srcdir"/> <attribute default="${build.classes.dir}" name="destdir"/> <attribute default="${javac.classpath}" name="classpath"/> <sequential> <depend cache="${build.dir}/depcache" destdir="@{destdir}" excludes="${excludes}" includes="${includes}" srcdir="@{srcdir}"> <classpath> <path path="@{classpath}"/> </classpath> </depend> </sequential> </macrodef> <macrodef name="force-recompile" uri="http://www.netbeans.org/ns/j2se-project/3"> <attribute default="${build.classes.dir}" name="destdir"/> <sequential> <fail unless="javac.includes">Must set javac.includes</fail> <pathconvert pathsep="," property="javac.includes.binary"> <path> <filelist dir="@{destdir}" files="${javac.includes}"/> </path> <globmapper from="*.java" to="*.class"/> </pathconvert> <delete> <files includes="${javac.includes.binary}"/> </delete> </sequential> </macrodef> </target> <target name="-init-macrodef-junit"> <macrodef name="junit" uri="http://www.netbeans.org/ns/j2se-project/3"> <attribute default="${includes}" name="includes"/> <attribute default="${excludes}" name="excludes"/> <attribute default="**" name="testincludes"/> <sequential> <junit dir="${work.dir}" errorproperty="tests.failed" failureproperty="tests.failed" fork="true" showoutput="true" tempdir="${build.dir}"> <batchtest todir="${build.test.results.dir}"> <fileset dir="${test.src.dir}" excludes="@{excludes},${excludes}" includes="@{includes}"> <filename name="@{testincludes}"/> </fileset> </batchtest> <classpath> <path path="${run.test.classpath}"/> </classpath> <syspropertyset> <propertyref prefix="test-sys-prop."/> <mapper from="test-sys-prop.*" to="*" type="glob"/> </syspropertyset> <formatter type="brief" usefile="false"/> <formatter type="xml"/> <jvmarg line="${endorsed.classpath.cmd.line.arg}"/> <jvmarg line="${run.jvmargs}"/> </junit> </sequential> </macrodef> </target> <target depends="-init-debug-args" name="-init-macrodef-nbjpda"> <macrodef name="nbjpdastart" uri="http://www.netbeans.org/ns/j2se-project/1"> <attribute default="${main.class}" name="name"/> <attribute default="${debug.classpath}" name="classpath"/> <attribute default="" name="stopclassname"/> <sequential> <nbjpdastart addressproperty="jpda.address" name="@{name}" stopclassname="@{stopclassname}" transport="${debug-transport}"> <classpath> <path path="@{classpath}"/> </classpath> </nbjpdastart> </sequential> </macrodef> <macrodef name="nbjpdareload" uri="http://www.netbeans.org/ns/j2se-project/1"> <attribute default="${build.classes.dir}" name="dir"/> <sequential> <nbjpdareload> <fileset dir="@{dir}" includes="${fix.classes}"> <include name="${fix.includes}*.class"/> </fileset> </nbjpdareload> </sequential> </macrodef> </target> <target name="-init-debug-args"> <property name="version-output" value="java version &quot;${ant.java.version}"/> <condition property="have-jdk-older-than-1.4"> <or> <contains string="${version-output}" substring="java version &quot;1.0"/> <contains string="${version-output}" substring="java version &quot;1.1"/> <contains string="${version-output}" substring="java version &quot;1.2"/> <contains string="${version-output}" substring="java version &quot;1.3"/> </or> </condition> <condition else="-Xdebug" property="debug-args-line" value="-Xdebug -Xnoagent -Djava.compiler=none"> <istrue value="${have-jdk-older-than-1.4}"/> </condition> <condition else="dt_socket" property="debug-transport-by-os" value="dt_shmem"> <os family="windows"/> </condition> <condition else="${debug-transport-by-os}" property="debug-transport" value="${debug.transport}"> <isset property="debug.transport"/> </condition> </target> <target depends="-init-debug-args" name="-init-macrodef-debug"> <macrodef name="debug" uri="http://www.netbeans.org/ns/j2se-project/3"> <attribute default="${main.class}" name="classname"/> <attribute default="${debug.classpath}" name="classpath"/> <element name="customize" optional="true"/> <sequential> <java classname="@{classname}" dir="${work.dir}" fork="true"> <jvmarg line="${endorsed.classpath.cmd.line.arg}"/> <jvmarg line="${debug-args-line}"/> <jvmarg value="-Xrunjdwp:transport=${debug-transport},address=${jpda.address}"/> <jvmarg value="-Dfile.encoding=${runtime.encoding}"/> <redirector errorencoding="${runtime.encoding}" inputencoding="${runtime.encoding}" outputencoding="${runtime.encoding}"/> <jvmarg line="${run.jvmargs}"/> <classpath> <path path="@{classpath}"/> </classpath> <syspropertyset> <propertyref prefix="run-sys-prop."/> <mapper from="run-sys-prop.*" to="*" type="glob"/> </syspropertyset> <customize/> </java> </sequential> </macrodef> </target> <target name="-init-macrodef-java"> <macrodef name="java" uri="http://www.netbeans.org/ns/j2se-project/1"> <attribute default="${main.class}" name="classname"/> <attribute default="${run.classpath}" name="classpath"/> <element name="customize" optional="true"/> <sequential> <java classname="@{classname}" dir="${work.dir}" fork="true"> <jvmarg line="${endorsed.classpath.cmd.line.arg}"/> <jvmarg value="-Dfile.encoding=${runtime.encoding}"/> <redirector errorencoding="${runtime.encoding}" inputencoding="${runtime.encoding}" outputencoding="${runtime.encoding}"/> <jvmarg line="${run.jvmargs}"/> <classpath> <path path="@{classpath}"/> </classpath> <syspropertyset> <propertyref prefix="run-sys-prop."/> <mapper from="run-sys-prop.*" to="*" type="glob"/> </syspropertyset> <customize/> </java> </sequential> </macrodef> </target> <target name="-init-presetdef-jar"> <presetdef name="jar" uri="http://www.netbeans.org/ns/j2se-project/1"> <jar compress="${jar.compress}" jarfile="${dist.jar}"> <j2seproject1:fileset dir="${build.classes.dir}"/> </jar> </presetdef> </target> <target depends="-pre-init,-init-private,-init-user,-init-project,-do-init,-post-init,-init-check,-init-macrodef-property,-init-macrodef-javac,-init-macrodef-junit,-init-macrodef-nbjpda,-init-macrodef-debug,-init-macrodef-java,-init-presetdef-jar" name="init"/> <!-- =================== COMPILATION SECTION =================== --> <target name="-deps-jar-init" unless="built-jar.properties"> <property location="${build.dir}/built-jar.properties" name="built-jar.properties"/> <delete file="${built-jar.properties}" quiet="true"/> </target> <target if="already.built.jar.${basedir}" name="-warn-already-built-jar"> <echo level="warn" message="Cycle detected: eye was already built"/> </target> <target depends="init,-deps-jar-init" name="deps-jar" unless="no.deps"> <mkdir dir="${build.dir}"/> <touch file="${built-jar.properties}" verbose="false"/> <property file="${built-jar.properties}" prefix="already.built.jar."/> <antcall target="-warn-already-built-jar"/> <propertyfile file="${built-jar.properties}"> <entry key="${basedir}" value=""/> </propertyfile> <antcall target="-maybe-call-dep"> <param name="call.built.properties" value="${built-jar.properties}"/> <param location="${project.DB4o-Server}" name="call.subproject"/> <param location="${project.DB4o-Server}/build.xml" name="call.script"/> <param name="call.target" value="jar"/> <param name="transfer.built-jar.properties" value="${built-jar.properties}"/> </antcall> + <antcall target="-maybe-call-dep"> + <param name="call.built.properties" value="${built-jar.properties}"/> + <param location="${project.EyeCore}" name="call.subproject"/> + <param location="${project.EyeCore}/build.xml" name="call.script"/> + <param name="call.target" value="jar"/> + <param name="transfer.built-jar.properties" value="${built-jar.properties}"/> + </antcall> </target> <target depends="init,-check-automatic-build,-clean-after-automatic-build" name="-verify-automatic-build"/> <target depends="init" name="-check-automatic-build"> <available file="${build.classes.dir}/.netbeans_automatic_build" property="netbeans.automatic.build"/> </target> <target depends="init" if="netbeans.automatic.build" name="-clean-after-automatic-build"> <antcall target="clean"/> </target> <target depends="init,deps-jar" name="-pre-pre-compile"> <mkdir dir="${build.classes.dir}"/> </target> <target name="-pre-compile"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> </target> <target if="do.depend.true" name="-compile-depend"> <pathconvert property="build.generated.subdirs"> <dirset dir="${build.generated.sources.dir}" erroronmissingdir="false"> <include name="*"/> </dirset> </pathconvert> <j2seproject3:depend srcdir="${src.dir}:${build.generated.subdirs}"/> </target> <target depends="init,deps-jar,-pre-pre-compile,-pre-compile,-compile-depend" if="have.sources" name="-do-compile"> <j2seproject3:javac gensrcdir="${build.generated.sources.dir}"/> <copy todir="${build.classes.dir}"> <fileset dir="${src.dir}" excludes="${build.classes.excludes},${excludes}" includes="${includes}"/> </copy> </target> <target name="-post-compile"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> </target> <target depends="init,deps-jar,-verify-automatic-build,-pre-pre-compile,-pre-compile,-do-compile,-post-compile" description="Compile project." name="compile"/> <target name="-pre-compile-single"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> </target> <target depends="init,deps-jar,-pre-pre-compile" name="-do-compile-single"> <fail unless="javac.includes">Must select some files in the IDE or set javac.includes</fail> <j2seproject3:force-recompile/> <j2seproject3:javac excludes="" gensrcdir="${build.generated.sources.dir}" includes="${javac.includes}" sourcepath="${src.dir}"/> </target> <target name="-post-compile-single"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> </target> <target depends="init,deps-jar,-verify-automatic-build,-pre-pre-compile,-pre-compile-single,-do-compile-single,-post-compile-single" name="compile-single"/> <!-- ==================== JAR BUILDING SECTION ==================== --> <target depends="init" name="-pre-pre-jar"> <dirname file="${dist.jar}" property="dist.jar.dir"/> <mkdir dir="${dist.jar.dir}"/> </target> <target name="-pre-jar"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> </target> <target depends="init,compile,-pre-pre-jar,-pre-jar" name="-do-jar-without-manifest" unless="manifest.available-mkdist.available"> <j2seproject1:jar/> </target> <target depends="init,compile,-pre-pre-jar,-pre-jar" if="manifest.available" name="-do-jar-with-manifest" unless="manifest.available+main.class-mkdist.available"> <j2seproject1:jar manifest="${manifest.file}"/> </target> <target depends="init,compile,-pre-pre-jar,-pre-jar" if="manifest.available+main.class" name="-do-jar-with-mainclass" unless="manifest.available+main.class+mkdist.available"> <j2seproject1:jar manifest="${manifest.file}"> <j2seproject1:manifest> <j2seproject1:attribute name="Main-Class" value="${main.class}"/> </j2seproject1:manifest> </j2seproject1:jar> <echo>To run this application from the command line without Ant, try:</echo> <property location="${build.classes.dir}" name="build.classes.dir.resolved"/> <property location="${dist.jar}" name="dist.jar.resolved"/> <pathconvert property="run.classpath.with.dist.jar"> <path path="${run.classpath}"/> <map from="${build.classes.dir.resolved}" to="${dist.jar.resolved}"/> </pathconvert> <echo>java -cp "${run.classpath.with.dist.jar}" ${main.class}</echo> </target> <target depends="init,compile,-pre-pre-jar,-pre-jar" if="manifest.available+main.class+mkdist.available" name="-do-jar-with-libraries"> <property location="${build.classes.dir}" name="build.classes.dir.resolved"/> <pathconvert property="run.classpath.without.build.classes.dir"> <path path="${run.classpath}"/> <map from="${build.classes.dir.resolved}" to=""/> </pathconvert> <pathconvert pathsep=" " property="jar.classpath"> <path path="${run.classpath.without.build.classes.dir}"/> <chainedmapper> <flattenmapper/> <globmapper from="*" to="lib/*"/> </chainedmapper> </pathconvert> <taskdef classname="org.netbeans.modules.java.j2seproject.copylibstask.CopyLibs" classpath="${libs.CopyLibs.classpath}" name="copylibs"/> <copylibs compress="${jar.compress}" jarfile="${dist.jar}" manifest="${manifest.file}" runtimeclasspath="${run.classpath.without.build.classes.dir}"> <fileset dir="${build.classes.dir}"/> <manifest> <attribute name="Main-Class" value="${main.class}"/> <attribute name="Class-Path" value="${jar.classpath}"/> </manifest> </copylibs> <echo>To run this application from the command line without Ant, try:</echo> <property location="${dist.jar}" name="dist.jar.resolved"/> <echo>java -jar "${dist.jar.resolved}"</echo> </target> <target depends="init,compile,-pre-pre-jar,-pre-jar" if="manifest.available+mkdist.available" name="-do-jar-with-libraries-without-mainclass" unless="main.class.available"> <property location="${build.classes.dir}" name="build.classes.dir.resolved"/> <pathconvert property="run.classpath.without.build.classes.dir"> <path path="${run.classpath}"/> <map from="${build.classes.dir.resolved}" to=""/> </pathconvert> <pathconvert pathsep=" " property="jar.classpath"> <path path="${run.classpath.without.build.classes.dir}"/> <chainedmapper> <flattenmapper/> <globmapper from="*" to="lib/*"/> </chainedmapper> </pathconvert> <taskdef classname="org.netbeans.modules.java.j2seproject.copylibstask.CopyLibs" classpath="${libs.CopyLibs.classpath}" name="copylibs"/> <copylibs compress="${jar.compress}" jarfile="${dist.jar}" manifest="${manifest.file}" runtimeclasspath="${run.classpath.without.build.classes.dir}"> <fileset dir="${build.classes.dir}"/> <manifest> <attribute name="Class-Path" value="${jar.classpath}"/> </manifest> </copylibs> </target> <target depends="init,compile,-pre-pre-jar,-pre-jar" if="do.mkdist" name="-do-jar-with-libraries-without-manifest" unless="manifest.available"> <property location="${build.classes.dir}" name="build.classes.dir.resolved"/> <pathconvert property="run.classpath.without.build.classes.dir"> <path path="${run.classpath}"/> <map from="${build.classes.dir.resolved}" to=""/> </pathconvert> <pathconvert pathsep=" " property="jar.classpath"> <path path="${run.classpath.without.build.classes.dir}"/> <chainedmapper> <flattenmapper/> <globmapper from="*" to="lib/*"/> </chainedmapper> </pathconvert> <taskdef classname="org.netbeans.modules.java.j2seproject.copylibstask.CopyLibs" classpath="${libs.CopyLibs.classpath}" name="copylibs"/> <copylibs compress="${jar.compress}" jarfile="${dist.jar}" runtimeclasspath="${run.classpath.without.build.classes.dir}"> <fileset dir="${build.classes.dir}"/> <manifest> <attribute name="Class-Path" value="${jar.classpath}"/> </manifest> </copylibs> </target> <target name="-post-jar"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> </target> <target depends="init,compile,-pre-jar,-do-jar-with-manifest,-do-jar-without-manifest,-do-jar-with-mainclass,-do-jar-with-libraries,-do-jar-with-libraries-without-mainclass,-do-jar-with-libraries-without-manifest,-post-jar" description="Build JAR." name="jar"/> <!-- ================= EXECUTION SECTION ================= --> <target depends="init,compile" description="Run a main class." name="run"> <j2seproject1:java> <customize> <arg line="${application.args}"/> </customize> </j2seproject1:java> </target> <target name="-do-not-recompile"> <property name="javac.includes.binary" value=""/> </target> <target depends="init,compile-single" name="run-single"> <fail unless="run.class">Must select one file in the IDE or set run.class</fail> <j2seproject1:java classname="${run.class}"/> </target> <target depends="init,compile-test-single" name="run-test-with-main"> <fail unless="run.class">Must select one file in the IDE or set run.class</fail> <j2seproject1:java classname="${run.class}" classpath="${run.test.classpath}"/> </target> <!-- ================= DEBUGGING SECTION ================= --> <target depends="init" if="netbeans.home" name="-debug-start-debugger"> <j2seproject1:nbjpdastart name="${debug.class}"/> </target> <target depends="init" if="netbeans.home" name="-debug-start-debugger-main-test"> <j2seproject1:nbjpdastart classpath="${debug.test.classpath}" name="${debug.class}"/> </target> <target depends="init,compile" name="-debug-start-debuggee"> <j2seproject3:debug> <customize> <arg line="${application.args}"/> </customize> </j2seproject3:debug> </target> <target depends="init,compile,-debug-start-debugger,-debug-start-debuggee" description="Debug project in IDE." if="netbeans.home" name="debug"/> <target depends="init" if="netbeans.home" name="-debug-start-debugger-stepinto"> <j2seproject1:nbjpdastart stopclassname="${main.class}"/> </target> <target depends="init,compile,-debug-start-debugger-stepinto,-debug-start-debuggee" if="netbeans.home" name="debug-stepinto"/> <target depends="init,compile-single" if="netbeans.home" name="-debug-start-debuggee-single"> <fail unless="debug.class">Must select one file in the IDE or set debug.class</fail> <j2seproject3:debug classname="${debug.class}"/> </target> <target depends="init,compile-single,-debug-start-debugger,-debug-start-debuggee-single" if="netbeans.home" name="debug-single"/> <target depends="init,compile-test-single" if="netbeans.home" name="-debug-start-debuggee-main-test"> <fail unless="debug.class">Must select one file in the IDE or set debug.class</fail> <j2seproject3:debug classname="${debug.class}" classpath="${debug.test.classpath}"/> </target> <target depends="init,compile-test-single,-debug-start-debugger-main-test,-debug-start-debuggee-main-test" if="netbeans.home" name="debug-test-with-main"/> <target depends="init" name="-pre-debug-fix"> <fail unless="fix.includes">Must set fix.includes</fail> <property name="javac.includes" value="${fix.includes}.java"/> </target> <target depends="init,-pre-debug-fix,compile-single" if="netbeans.home" name="-do-debug-fix"> <j2seproject1:nbjpdareload/> </target> <target depends="init,-pre-debug-fix,-do-debug-fix" if="netbeans.home" name="debug-fix"/> <!-- =============== JAVADOC SECTION =============== --> <target depends="init" name="-javadoc-build"> <mkdir dir="${dist.javadoc.dir}"/> <javadoc additionalparam="${javadoc.additionalparam}" author="${javadoc.author}" charset="UTF-8" destdir="${dist.javadoc.dir}" docencoding="UTF-8" encoding="${javadoc.encoding.used}" failonerror="true" noindex="${javadoc.noindex}" nonavbar="${javadoc.nonavbar}" notree="${javadoc.notree}" private="${javadoc.private}" source="${javac.source}" splitindex="${javadoc.splitindex}" use="${javadoc.use}" useexternalfile="true" version="${javadoc.version}" windowtitle="${javadoc.windowtitle}"> <classpath> <path path="${javac.classpath}"/> </classpath> <fileset dir="${src.dir}" excludes="${excludes}" includes="${includes}"> <filename name="**/*.java"/> </fileset> <fileset dir="${build.generated.sources.dir}" erroronmissingdir="false"> <include name="**/*.java"/> </fileset> </javadoc> </target> <target depends="init,-javadoc-build" if="netbeans.home" name="-javadoc-browse" unless="no.javadoc.preview"> <nbbrowse file="${dist.javadoc.dir}/index.html"/> </target> <target depends="init,-javadoc-build,-javadoc-browse" description="Build Javadoc." name="javadoc"/> <!-- ========================= JUNIT COMPILATION SECTION ========================= --> <target depends="init,compile" if="have.tests" name="-pre-pre-compile-test"> <mkdir dir="${build.test.classes.dir}"/> </target> <target name="-pre-compile-test"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> </target> <target if="do.depend.true" name="-compile-test-depend"> <j2seproject3:depend classpath="${javac.test.classpath}" destdir="${build.test.classes.dir}" srcdir="${test.src.dir}"/> </target> <target depends="init,compile,-pre-pre-compile-test,-pre-compile-test,-compile-test-depend" if="have.tests" name="-do-compile-test"> <j2seproject3:javac classpath="${javac.test.classpath}" debug="true" destdir="${build.test.classes.dir}" srcdir="${test.src.dir}"/> <copy todir="${build.test.classes.dir}"> <fileset dir="${test.src.dir}" excludes="${build.classes.excludes},${excludes}" includes="${includes}"/> </copy> </target> <target name="-post-compile-test"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> </target> <target depends="init,compile,-pre-pre-compile-test,-pre-compile-test,-do-compile-test,-post-compile-test" name="compile-test"/> <target name="-pre-compile-test-single"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> </target> <target depends="init,compile,-pre-pre-compile-test,-pre-compile-test-single" if="have.tests" name="-do-compile-test-single"> <fail unless="javac.includes">Must select some files in the IDE or set javac.includes</fail> <j2seproject3:force-recompile destdir="${build.test.classes.dir}"/> <j2seproject3:javac classpath="${javac.test.classpath}" debug="true" destdir="${build.test.classes.dir}" excludes="" includes="${javac.includes}" sourcepath="${test.src.dir}" srcdir="${test.src.dir}"/> <copy todir="${build.test.classes.dir}"> <fileset dir="${test.src.dir}" excludes="${build.classes.excludes},${excludes}" includes="${includes}"/> </copy> </target> <target name="-post-compile-test-single"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> </target> <target depends="init,compile,-pre-pre-compile-test,-pre-compile-test-single,-do-compile-test-single,-post-compile-test-single" name="compile-test-single"/> <!-- ======================= JUNIT EXECUTION SECTION ======================= --> <target depends="init" if="have.tests" name="-pre-test-run"> <mkdir dir="${build.test.results.dir}"/> </target> <target depends="init,compile-test,-pre-test-run" if="have.tests" name="-do-test-run"> <j2seproject3:junit testincludes="**/*Test.java"/> </target> <target depends="init,compile-test,-pre-test-run,-do-test-run" if="have.tests" name="-post-test-run"> <fail if="tests.failed" unless="ignore.failing.tests">Some tests failed; see details above.</fail> </target> <target depends="init" if="have.tests" name="test-report"/> <target depends="init" if="netbeans.home+have.tests" name="-test-browse"/> <target depends="init,compile-test,-pre-test-run,-do-test-run,test-report,-post-test-run,-test-browse" description="Run unit tests." name="test"/> <target depends="init" if="have.tests" name="-pre-test-run-single"> <mkdir dir="${build.test.results.dir}"/> </target> <target depends="init,compile-test-single,-pre-test-run-single" if="have.tests" name="-do-test-run-single"> <fail unless="test.includes">Must select some files in the IDE or set test.includes</fail> <j2seproject3:junit excludes="" includes="${test.includes}"/> </target> <target depends="init,compile-test-single,-pre-test-run-single,-do-test-run-single" if="have.tests" name="-post-test-run-single"> <fail if="tests.failed" unless="ignore.failing.tests">Some tests failed; see details above.</fail> </target> <target depends="init,compile-test-single,-pre-test-run-single,-do-test-run-single,-post-test-run-single" description="Run single unit test." name="test-single"/> <!-- ======================= JUNIT DEBUGGING SECTION ======================= --> <target depends="init,compile-test" if="have.tests" name="-debug-start-debuggee-test"> <fail unless="test.class">Must select one file in the IDE or set test.class</fail> <property location="${build.test.results.dir}/TEST-${test.class}.xml" name="test.report.file"/> <delete file="${test.report.file}"/> <mkdir dir="${build.test.results.dir}"/> <j2seproject3:debug classname="org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner" classpath="${ant.home}/lib/ant.jar:${ant.home}/lib/ant-junit.jar:${debug.test.classpath}"> <customize> <syspropertyset> <propertyref prefix="test-sys-prop."/> <mapper from="test-sys-prop.*" to="*" type="glob"/> </syspropertyset> <arg value="${test.class}"/> <arg value="showoutput=true"/> <arg value="formatter=org.apache.tools.ant.taskdefs.optional.junit.BriefJUnitResultFormatter"/> <arg value="formatter=org.apache.tools.ant.taskdefs.optional.junit.XMLJUnitResultFormatter,${test.report.file}"/> </customize> </j2seproject3:debug> </target> <target depends="init,compile-test" if="netbeans.home+have.tests" name="-debug-start-debugger-test"> <j2seproject1:nbjpdastart classpath="${debug.test.classpath}" name="${test.class}"/> </target> <target depends="init,compile-test-single,-debug-start-debugger-test,-debug-start-debuggee-test" name="debug-test"/> <target depends="init,-pre-debug-fix,compile-test-single" if="netbeans.home" name="-do-debug-fix-test"> <j2seproject1:nbjpdareload dir="${build.test.classes.dir}"/> </target> <target depends="init,-pre-debug-fix,-do-debug-fix-test" if="netbeans.home" name="debug-fix-test"/> <!-- ========================= APPLET EXECUTION SECTION ========================= --> <target depends="init,compile-single" name="run-applet"> <fail unless="applet.url">Must select one file in the IDE or set applet.url</fail> <j2seproject1:java classname="sun.applet.AppletViewer"> <customize> <arg value="${applet.url}"/> </customize> </j2seproject1:java> </target> <!-- ========================= APPLET DEBUGGING SECTION ========================= --> <target depends="init,compile-single" if="netbeans.home" name="-debug-start-debuggee-applet"> <fail unless="applet.url">Must select one file in the IDE or set applet.url</fail> <j2seproject3:debug classname="sun.applet.AppletViewer"> <customize> <arg value="${applet.url}"/> </customize> </j2seproject3:debug> </target> <target depends="init,compile-single,-debug-start-debugger,-debug-start-debuggee-applet" if="netbeans.home" name="debug-applet"/> <!-- =============== CLEANUP SECTION =============== --> <target name="-deps-clean-init" unless="built-clean.properties"> <property location="${build.dir}/built-clean.properties" name="built-clean.properties"/> <delete file="${built-clean.properties}" quiet="true"/> </target> <target if="already.built.clean.${basedir}" name="-warn-already-built-clean"> <echo level="warn" message="Cycle detected: eye was already built"/> </target> <target depends="init,-deps-clean-init" name="deps-clean" unless="no.deps"> <mkdir dir="${build.dir}"/> <touch file="${built-clean.properties}" verbose="false"/> <property file="${built-clean.properties}" prefix="already.built.clean."/> <antcall target="-warn-already-built-clean"/> <propertyfile file="${built-clean.properties}"> <entry key="${basedir}" value=""/> </propertyfile> <antcall target="-maybe-call-dep"> <param name="call.built.properties" value="${built-clean.properties}"/> <param location="${project.DB4o-Server}" name="call.subproject"/> <param location="${project.DB4o-Server}/build.xml" name="call.script"/> <param name="call.target" value="clean"/> <param name="transfer.built-clean.properties" value="${built-clean.properties}"/> </antcall> + <antcall target="-maybe-call-dep"> + <param name="call.built.properties" value="${built-clean.properties}"/> + <param location="${project.EyeCore}" name="call.subproject"/> + <param location="${project.EyeCore}/build.xml" name="call.script"/> + <param name="call.target" value="clean"/> + <param name="transfer.built-clean.properties" value="${built-clean.properties}"/> + </antcall> </target> <target depends="init" name="-do-clean"> <delete dir="${build.dir}"/> <delete dir="${dist.dir}" followsymlinks="false" includeemptydirs="true"/> </target> <target name="-post-clean"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> </target> <target depends="init,deps-clean,-do-clean,-post-clean" description="Clean build products." name="clean"/> <target name="-check-call-dep"> <property file="${call.built.properties}" prefix="already.built."/> <condition property="should.call.dep"> <not> <isset property="already.built.${call.subproject}"/> </not> </condition> </target> <target depends="-check-call-dep" if="should.call.dep" name="-maybe-call-dep"> <ant antfile="${call.script}" inheritall="false" target="${call.target}"> <propertyset> <propertyref prefix="transfer."/> <mapper from="transfer.*" to="*" type="glob"/> </propertyset> </ant> </target> </project> diff --git a/nbproject/genfiles.properties b/nbproject/genfiles.properties index b1f8948..a33f670 100644 --- a/nbproject/genfiles.properties +++ b/nbproject/genfiles.properties @@ -1,8 +1,8 @@ -build.xml.data.CRC32=c7637cc6 +build.xml.data.CRC32=bbba49eb build.xml.script.CRC32=809b2dff [email protected] # This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. # Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. -nbproject/build-impl.xml.data.CRC32=c7637cc6 -nbproject/build-impl.xml.script.CRC32=040939fe +nbproject/build-impl.xml.data.CRC32=bbba49eb +nbproject/build-impl.xml.script.CRC32=66b725db nbproject/[email protected] diff --git a/nbproject/private/.svn/entries b/nbproject/private/.svn/entries index 4cc8fb7..7ae24b6 100644 --- a/nbproject/private/.svn/entries +++ b/nbproject/private/.svn/entries @@ -1,130 +1,130 @@ 10 dir -19 +70 svn://localhost/spr1ngsvn/TheEye/Eye/nbproject/private svn://localhost/spr1ngsvn/TheEye 2010-06-28T07:29:35.843368Z 10 spr1ng 8763ed6d-9318-4032-b958-c511fcb819a9 config.properties file 2010-06-28T07:30:12.643069Z d41d8cd98f00b204e9800998ecf8427e 2010-06-28T07:29:35.843368Z 10 spr1ng 0 private.properties file 2010-06-28T07:30:12.643069Z 4553f6161b521153f5e430e30fdf12f9 2010-06-28T07:29:35.843368Z 10 spr1ng 232 private.xml file 2010-06-28T07:30:12.643069Z 325a3f155f66f3ce2c7df37de2bf87c6 2010-06-28T07:29:35.843368Z 10 spr1ng 548 diff --git a/nbproject/project.properties b/nbproject/project.properties index 2b08b75..4e866c4 100644 --- a/nbproject/project.properties +++ b/nbproject/project.properties @@ -1,73 +1,76 @@ application.title=eye application.vendor=Admin build.classes.dir=${build.dir}/classes build.classes.excludes=**/*.java,**/*.form # This directory is removed when the project is cleaned: build.dir=build build.generated.dir=${build.dir}/generated build.generated.sources.dir=${build.dir}/generated-sources # Only compile against the classpath explicitly listed here: build.sysclasspath=ignore build.test.classes.dir=${build.dir}/test/classes build.test.results.dir=${build.dir}/test/results # Uncomment to specify the preferred debugger connection transport: #debug.transport=dt_socket debug.classpath=\ ${run.classpath} debug.test.classpath=\ ${run.test.classpath} # This directory is removed when the project is cleaned: dist.dir=dist dist.jar=${dist.dir}/eye.jar dist.javadoc.dir=${dist.dir}/javadoc endorsed.classpath= excludes= -file.reference.db4o-7.12.145.14409-all-java5.jar=../DB4o-Server/libs/db4o-7.12.145.14409-all-java5.jar +file.reference.db4o-7.12.145.14409-all-java5.jar=libs/db4o-7.12.145.14409-all-java5.jar file.reference.log4j-1.2.15.jar=libs\\log4j-1.2.15.jar includes=** jar.compress=false javac.classpath=\ ${reference.DB4o-Server.jar}:\ + ${reference.EyeCore.jar}:\ ${file.reference.log4j-1.2.15.jar}:\ ${file.reference.db4o-7.12.145.14409-all-java5.jar} # Space-separated list of extra javac options javac.compilerargs= javac.deprecation=false javac.source=1.5 javac.target=1.5 javac.test.classpath=\ ${javac.classpath}:\ ${build.classes.dir}:\ ${libs.junit.classpath}:\ ${libs.junit_4.classpath} javadoc.additionalparam= javadoc.author=false javadoc.encoding=${source.encoding} javadoc.noindex=false javadoc.nonavbar=false javadoc.notree=false javadoc.private=false javadoc.splitindex=true javadoc.use=true javadoc.version=false javadoc.windowtitle= jaxbwiz.endorsed.dirs="${netbeans.home}/../ide12/modules/ext/jaxb/api" -main.class=eye.Eye +main.class=eye.crawler.Crawler manifest.file=manifest.mf meta.inf.dir=${src.dir}/META-INF platform.active=default_platform project.DB4o-Server=../DB4o-Server +project.EyeCore=../EyeCore reference.DB4o-Server.jar=${project.DB4o-Server}/dist/DB4o-Server.jar +reference.EyeCore.jar=${project.EyeCore}/dist/EyeCore.jar run.classpath=\ ${javac.classpath}:\ ${build.classes.dir} # Space-separated list of JVM arguments used when running the project # (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value # or test-sys-prop.name=value to set system properties for unit tests): run.jvmargs= run.test.classpath=\ ${javac.test.classpath}:\ ${build.test.classes.dir} source.encoding=UTF-8 src.dir=src test.src.dir=test diff --git a/nbproject/project.xml b/nbproject/project.xml index 24b7095..99af66c 100644 --- a/nbproject/project.xml +++ b/nbproject/project.xml @@ -1,25 +1,33 @@ <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://www.netbeans.org/ns/project/1"> <type>org.netbeans.modules.java.j2seproject</type> <configuration> <data xmlns="http://www.netbeans.org/ns/j2se-project/3"> <name>eye</name> <source-roots> <root id="src.dir"/> </source-roots> <test-roots> <root id="test.src.dir"/> </test-roots> </data> <references xmlns="http://www.netbeans.org/ns/ant-project-references/1"> <reference> <foreign-project>DB4o-Server</foreign-project> <artifact-type>jar</artifact-type> <script>build.xml</script> <target>jar</target> <clean-target>clean</clean-target> <id>jar</id> </reference> + <reference> + <foreign-project>EyeCore</foreign-project> + <artifact-type>jar</artifact-type> + <script>build.xml</script> + <target>jar</target> + <clean-target>clean</clean-target> + <id>jar</id> + </reference> </references> </configuration> </project> diff --git a/src/.svn/entries b/src/.svn/entries index e1872ca..72ca04e 100644 --- a/src/.svn/entries +++ b/src/.svn/entries @@ -1,65 +1,65 @@ 10 dir -19 +70 svn://localhost/spr1ngsvn/TheEye/Eye/src svn://localhost/spr1ngsvn/TheEye -2010-06-30T03:16:43.109433Z -19 -stream +2010-07-08T03:48:08.935715Z +70 +spr1ng 8763ed6d-9318-4032-b958-c511fcb819a9 eye dir log4j.xml file -delete -2010-06-28T07:30:12.679068Z + +2010-07-02T07:13:57.766566Z 7d0ca4dc1fd50bbf9008892c09c2ef8e 2010-06-28T07:29:35.843368Z 10 spr1ng 604 diff --git a/src/eye/.svn/entries b/src/eye/.svn/entries index 9c2433b..efcd5c1 100644 --- a/src/eye/.svn/entries +++ b/src/eye/.svn/entries @@ -1,173 +1,54 @@ 10 dir -19 +70 svn://localhost/spr1ngsvn/TheEye/Eye/src/eye svn://localhost/spr1ngsvn/TheEye -2010-06-30T03:16:43.109433Z -19 -stream - - - - - - - - - - - - - - -8763ed6d-9318-4032-b958-c511fcb819a9 - -IIException.java -file -24 - - - -2010-06-30T07:43:46.023066Z -f5fb86a8cd4dad4e8dd55a82614830b8 -2010-06-30T07:43:45.867637Z -24 +2010-07-08T03:48:08.935715Z +70 spr1ng -has-props - - - - - - -553 - -Eye.java -file -28 - - - -2010-07-01T05:35:24.774572Z -c337703e0f3200faa10c27a65f47a6e1 -2010-07-01T05:35:24.601857Z -28 -spr1ng -has-props - - - - - - - - - - - - +8763ed6d-9318-4032-b958-c511fcb819a9 -10412 +((conflict models dir update edited deleted (version svn://localhost/spr1ngsvn/TheEye 2 55 Eye/src/eye/models none) (version svn://localhost/spr1ngsvn/TheEye 2 69 Eye/src/eye/models dir)) (conflict net dir update edited deleted (version svn://localhost/spr1ngsvn/TheEye 2 55 Eye/src/eye/net none) (version svn://localhost/spr1ngsvn/TheEye 2 69 Eye/src/eye/net dir))) -models +crawler dir -config +models dir - -DBManagerEyeImpl.java -file -28 - - - -2010-07-01T05:35:24.774572Z -e827050bac515a771df6d037129c208d -2010-07-01T05:35:24.601857Z -28 -spr1ng -has-props - - - - - - - - - - - - - - - - - -3525 +delete net dir - -ImageFactory.java -file -28 - - - -2010-07-01T05:35:24.810571Z -3d1340fc8696be742bb67f6dc874a7e2 -2010-07-01T05:35:24.601857Z -28 -spr1ng -has-props - - - - - - - - - - - - - - - - - -4824 +delete diff --git a/src/eye/.svn/prop-base/Eye.java.svn-base b/src/eye/.svn/prop-base/Eye.java.svn-base deleted file mode 100644 index 92c8ad7..0000000 --- a/src/eye/.svn/prop-base/Eye.java.svn-base +++ /dev/null @@ -1,5 +0,0 @@ -K 12 -svn:keywords -V 2 -Id -END diff --git a/src/eye/.svn/prop-base/IIException.java.svn-base b/src/eye/.svn/prop-base/IIException.java.svn-base deleted file mode 100644 index 92c8ad7..0000000 --- a/src/eye/.svn/prop-base/IIException.java.svn-base +++ /dev/null @@ -1,5 +0,0 @@ -K 12 -svn:keywords -V 2 -Id -END diff --git a/src/eye/.svn/prop-base/ImageFactory.java.svn-base b/src/eye/.svn/prop-base/ImageFactory.java.svn-base deleted file mode 100644 index 92c8ad7..0000000 --- a/src/eye/.svn/prop-base/ImageFactory.java.svn-base +++ /dev/null @@ -1,5 +0,0 @@ -K 12 -svn:keywords -V 2 -Id -END diff --git a/src/eye/.svn/text-base/IIException.java.svn-base b/src/eye/.svn/text-base/IIException.java.svn-base deleted file mode 100644 index 2f8e2eb..0000000 --- a/src/eye/.svn/text-base/IIException.java.svn-base +++ /dev/null @@ -1,29 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package eye; - -import java.io.IOException; - -/** - * IncorrectImageException - * @author spr1ng - * @version $Id$ - */ -public class IIException extends IOException { - - public IIException(String message) { - super(message); - } - - public IIException(Throwable cause) { - super(cause); - } - - public IIException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/src/eye/.svn/text-base/ImageFactory.java.svn-base b/src/eye/.svn/text-base/ImageFactory.java.svn-base deleted file mode 100644 index 610cd6c..0000000 --- a/src/eye/.svn/text-base/ImageFactory.java.svn-base +++ /dev/null @@ -1,160 +0,0 @@ -package eye; - -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.image.BufferedImage; -import java.awt.image.BufferedImageOp; -import java.awt.image.ConvolveOp; -import java.awt.image.Kernel; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URL; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import javax.imageio.ImageIO; -import eye.models.Point; -import eye.models.Image; -import static eye.net.InetUtils.*; - -/** - * - * @author gpdribbler, spr1ng - * @version $Id$ - */ -public class ImageFactory { - - private final static int DEPTH = 25; - //TODO: сделать дисперсию долевой от размеров картинки - private final static int DISPERSION = 20; - private final static int MIN_WIDTH = 128; - private final static int MIN_HEIGHT = 128; - - private BufferedImage bimg; - private ArrayList<Point> points; - - public void load(File file) throws IOException { - bimg = ImageIO.read(file); - } - - public void load(URL url) throws IOException { - //Зададим-ка мы проверочку на таймаут - if (isReachable(url.toString(), 3000)) - bimg = ImageIO.read(url); - else throw new IIException("Connection timeout"); - } - - /** - * Создает BufferedImage из потока - * @param in входящий поток - * @throws IOException - */ - public void load(InputStream in) throws IOException { - bimg = ImageIO.read(in); - } - - public void saveToFile(String fileName) throws IOException { - ImageIO.write(bimg, getExtension(fileName), new File(fileName)); - } - - /** - * Saves to output stream - * @param imgExtension - * @param out - * @throws IOException - */ - public void saveToOutputStream(String imgExtension, OutputStream out) throws IOException { - ImageIO.write(bimg, imgExtension, out); - } - - /** - * Рисует области вокруг точек белым цветом - * @param points - */ - public void draw(List<Point> points) { - draw(points, Color.WHITE); - } - - /** - * Рисует области вокруг точек выбранным цветом - * @param points - * @param color - */ - public void draw(List<Point> points, Color color){ - int d = 20; - Graphics2D graphics = bimg.createGraphics(); - for (Iterator<Point> it = points.iterator(); it.hasNext();) { - Point point = it.next(); - graphics.setColor(color); - graphics.drawOval(point.getX()-(d/2), point.getY()-(d/2), d, d); - } - } - - public List<Point> seekPoints(InputStream in) throws IOException{ - load(in); - return seekPoints(); - } - - public List<Point> seekPoints(){ - try { - Kernel kernel = new Kernel(3, 3, new float[]{1f / 9f, 1f / 9f, 1f / 9f, - 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f}); - BufferedImageOp op = new ConvolveOp(kernel); - bimg = op.filter(bimg, null); - } catch (Exception e) { - } - - points = new ArrayList<Point>(); - - //TODO: проверить значение декремента - int w = bimg.getWidth()-4; - int h = bimg.getHeight()-4; - for(int i = 2; i < w; i++) - for(int j = 2; j < h; j++) { - Point point = new Point(i, j, bimg); - if(point.isBorder(DEPTH)) points.add(point); - }//for - - //TODO: увеличить эффективность за счет просмотра только ближайших точек - for(int i = 0; i < points.size(); i++) - for(int j = i+1; j < points.size(); j++) - if(points.get(i).compareTo(points.get(j)) < DISPERSION) { - points.remove(j); - j--; - } - - return points; - - }//seekPoints() - - private boolean hasValidSize() { - if( (bimg.getWidth() >= MIN_WIDTH) && (bimg.getHeight() >= MIN_HEIGHT) ) { - return true; - } else { - return false; - } - }//checkMeasurement - - public void produceMetaImage(Image image) throws IOException { - load(new URL(image.getUrl())); - - if(hasValidSize()) { - image.setPoints(seekPoints()); - System.out.println(image); - } else { - throw new IIException("Invalid image size."); - } - } - - /** - * Gets file extension - * @param fileName - * @return - */ - public static String getExtension(String fileName){ - return fileName.replaceFirst(".*\\.", ""); - } - -} diff --git a/src/eye/DBManagerEyeImpl.java b/src/eye/DBManagerEyeImpl.java deleted file mode 100644 index 2bcf93f..0000000 --- a/src/eye/DBManagerEyeImpl.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package eye; - -import com.db4o.ObjectContainer; -import com.db4o.ObjectSet; -import com.db4o.cs.Db4oClientServer; -import db4oserver.AbstractDBManager; -import db4oserver.ConfigLoader; -import eye.models.Image; -import eye.models.Place; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import org.apache.log4j.Logger; - -/** - * - * @author spr1ng - * @version $Id: DBManagerEyeImpl.java 28 2010-07-01 05:35:24Z spr1ng $ - */ -public class DBManagerEyeImpl extends AbstractDBManager{ - - private static ConfigLoader conf = ConfigLoader.getInstance(); - public static final Logger LOG = Logger.getLogger(DBManagerEyeImpl.class); - - public ObjectContainer getContainer() { - return Db4oClientServer.openClient(Db4oClientServer - .newClientConfiguration(), conf.getHost(), conf.getPort(), conf.getUser(), conf.getPass()); - } - - public void watchDb() { - ObjectContainer db = getContainer(); - try { - watchDb(db); - } finally { - db.close(); - } - } - - public void watchDb(ObjectContainer db) { - ObjectSet objects = db.query().execute(); - - int places = 0, images = 0; - for (Object object : objects) { - if (object instanceof Place) { - places++; - Place p = (Place) object; - LOG.info("Place url: " + p.getUrl()); - if (p.getDate() != null) { - LOG.info("Place data: " + p.getDate()); - } - } - } - LOG.info("-------> Total places: " + places); - for (Object object : objects) { - if (object instanceof Image) { - images++; - Image i = (Image) object; - LOG.info("Image: " + i.getUrl()); - if (i.getPoints() != null) { - LOG.info("!!!!!!!!!!!!!!!!!!!!!!!Points: " + i.getPoints()); - } - } - } - LOG.info("-------> Total images: " + images); - - LOG.info("Total objects: " + objects.size()); - } - - /** - * Сохраняет все объекты списка в базу. Возвращает количество новых - * сохраненных объектов - * @param objects - */ - public int store(List objects) { - if (objects == null) { - LOG.error("A try to store a null list of objects"); - return 0; - } - ObjectContainer db = getContainer(); - int qty = 0; - try { - for (Object o : objects) { - if (o != null) { - //Если такого объекта еще нет в базе - if (!isItemStored(o)) { - db.store(o); - qty++; - } //else LOG.error("A try to store a duplicate object"); //DELME: - } else LOG.error("A try to store a null object"); - } - } finally { db.close(); } - - return qty; - } - - /** Сохраняет место поиска глаза */ - public void storePlace(String firstPlace) { - //Инициализируем первое место поиска - try { - new URL(firstPlace); - } catch (MalformedURLException ex) { - LOG.error("Can't reach target: " + firstPlace, ex); - } - List<Place> places = new ArrayList<Place>(1); - places.add(new Place(firstPlace)); - store(places); - } - -} diff --git a/src/eye/IIException.java b/src/eye/IIException.java deleted file mode 100644 index 3682a91..0000000 --- a/src/eye/IIException.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package eye; - -import java.io.IOException; - -/** - * IncorrectImageException - * @author spr1ng - * @version $Id: IIException.java 24 2010-06-30 07:43:45Z spr1ng $ - */ -public class IIException extends IOException { - - public IIException(String message) { - super(message); - } - - public IIException(Throwable cause) { - super(cause); - } - - public IIException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/src/eye/ImageFactory.java b/src/eye/ImageFactory.java deleted file mode 100644 index 83d2ac9..0000000 --- a/src/eye/ImageFactory.java +++ /dev/null @@ -1,160 +0,0 @@ -package eye; - -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.image.BufferedImage; -import java.awt.image.BufferedImageOp; -import java.awt.image.ConvolveOp; -import java.awt.image.Kernel; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URL; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import javax.imageio.ImageIO; -import eye.models.Point; -import eye.models.Image; -import static eye.net.InetUtils.*; - -/** - * - * @author gpdribbler, spr1ng - * @version $Id: ImageFactory.java 28 2010-07-01 05:35:24Z spr1ng $ - */ -public class ImageFactory { - - private final static int DEPTH = 25; - //TODO: сделать дисперсию долевой от размеров картинки - private final static int DISPERSION = 20; - private final static int MIN_WIDTH = 128; - private final static int MIN_HEIGHT = 128; - - private BufferedImage bimg; - private ArrayList<Point> points; - - public void load(File file) throws IOException { - bimg = ImageIO.read(file); - } - - public void load(URL url) throws IOException { - //Зададим-ка мы проверочку на таймаут - if (isReachable(url.toString(), 3000)) - bimg = ImageIO.read(url); - else throw new IIException("Connection timeout"); - } - - /** - * Создает BufferedImage из потока - * @param in входящий поток - * @throws IOException - */ - public void load(InputStream in) throws IOException { - bimg = ImageIO.read(in); - } - - public void saveToFile(String fileName) throws IOException { - ImageIO.write(bimg, getExtension(fileName), new File(fileName)); - } - - /** - * Saves to output stream - * @param imgExtension - * @param out - * @throws IOException - */ - public void saveToOutputStream(String imgExtension, OutputStream out) throws IOException { - ImageIO.write(bimg, imgExtension, out); - } - - /** - * Рисует области вокруг точек белым цветом - * @param points - */ - public void draw(List<Point> points) { - draw(points, Color.WHITE); - } - - /** - * Рисует области вокруг точек выбранным цветом - * @param points - * @param color - */ - public void draw(List<Point> points, Color color){ - int d = 20; - Graphics2D graphics = bimg.createGraphics(); - for (Iterator<Point> it = points.iterator(); it.hasNext();) { - Point point = it.next(); - graphics.setColor(color); - graphics.drawOval(point.getX()-(d/2), point.getY()-(d/2), d, d); - } - } - - public List<Point> seekPoints(InputStream in) throws IOException{ - load(in); - return seekPoints(); - } - - public List<Point> seekPoints(){ - try { - Kernel kernel = new Kernel(3, 3, new float[]{1f / 9f, 1f / 9f, 1f / 9f, - 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f}); - BufferedImageOp op = new ConvolveOp(kernel); - bimg = op.filter(bimg, null); - } catch (Exception e) { - } - - points = new ArrayList<Point>(); - - //TODO: проверить значение декремента - int w = bimg.getWidth()-4; - int h = bimg.getHeight()-4; - for(int i = 2; i < w; i++) - for(int j = 2; j < h; j++) { - Point point = new Point(i, j, bimg); - if(point.isBorder(DEPTH)) points.add(point); - }//for - - //TODO: увеличить эффективность за счет просмотра только ближайших точек - for(int i = 0; i < points.size(); i++) - for(int j = i+1; j < points.size(); j++) - if(points.get(i).compareTo(points.get(j)) < DISPERSION) { - points.remove(j); - j--; - } - - return points; - - }//seekPoints() - - private boolean hasValidSize() { - if( (bimg.getWidth() >= MIN_WIDTH) && (bimg.getHeight() >= MIN_HEIGHT) ) { - return true; - } else { - return false; - } - }//checkMeasurement - - public void produceMetaImage(Image image) throws IOException { - load(new URL(image.getUrl())); - - if(hasValidSize()) { - image.setPoints(seekPoints()); - System.out.println(image); - } else { - throw new IIException("Invalid image size."); - } - } - - /** - * Gets file extension - * @param fileName - * @return - */ - public static String getExtension(String fileName){ - return fileName.replaceFirst(".*\\.", ""); - } - -} diff --git a/src/eye/config/.svn/entries b/src/eye/config/.svn/entries deleted file mode 100644 index 579e827..0000000 --- a/src/eye/config/.svn/entries +++ /dev/null @@ -1,28 +0,0 @@ -10 - -dir -19 -svn://localhost/spr1ngsvn/TheEye/Eye/src/eye/config -svn://localhost/spr1ngsvn/TheEye - - - -2010-06-28T07:29:35.843368Z -10 -spr1ng - - - - - - - - - - - - - - -8763ed6d-9318-4032-b958-c511fcb819a9 - diff --git a/src/eye/crawler/.svn/entries b/src/eye/crawler/.svn/entries new file mode 100644 index 0000000..7421271 --- /dev/null +++ b/src/eye/crawler/.svn/entries @@ -0,0 +1,62 @@ +10 + +dir +70 +svn://localhost/spr1ngsvn/TheEye/Eye/src/eye/crawler +svn://localhost/spr1ngsvn/TheEye + + + +2010-07-08T03:44:15.120757Z +62 +spr1ng + + + + + + + + + + + + + + +8763ed6d-9318-4032-b958-c511fcb819a9 + +Crawler.java +file + + + + +2010-07-08T03:44:15.242585Z +cfe7761a3ebfe46dfe84f2ff3f90015f +2010-07-08T03:44:15.120757Z +62 +spr1ng +has-props + + + + + + + + + + + + + + + + + + + + +10925 + diff --git a/src/eye/.svn/prop-base/DBManagerEyeImpl.java.svn-base b/src/eye/crawler/.svn/prop-base/Crawler.java.svn-base similarity index 100% rename from src/eye/.svn/prop-base/DBManagerEyeImpl.java.svn-base rename to src/eye/crawler/.svn/prop-base/Crawler.java.svn-base diff --git a/src/eye/Eye.java b/src/eye/crawler/.svn/text-base/Crawler.java.svn-base similarity index 84% rename from src/eye/Eye.java rename to src/eye/crawler/.svn/text-base/Crawler.java.svn-base index 4c1870a..9af3496 100644 --- a/src/eye/Eye.java +++ b/src/eye/crawler/.svn/text-base/Crawler.java.svn-base @@ -1,296 +1,307 @@ -package eye; +package eye.crawler; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Date; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.net.URL; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.util.HashSet; import java.util.Set; import org.apache.log4j.Logger; import com.db4o.ObjectContainer; import com.db4o.ObjectSet; import com.db4o.query.Query; -import eye.models.Image; -import eye.models.Place; -import static eye.net.InetUtils.*; +import eye.core.model.Image; +import eye.core.model.Place; +import eye.server.manager.impl.DBManagerBasicImpl; /** - * The Eye - yet another crawler ;) + * The Crawler - yet another crawler ;) * @author gpdribbler, spr1ng - * @version $Id: Eye.java 28 2010-07-01 05:35:24Z spr1ng $ + * @version $Id$ */ -public class Eye { - private static final Logger LOG = Logger.getLogger(Eye.class); - private static DBManagerEyeImpl dbm = new DBManagerEyeImpl(); +public class Crawler { + private static final Logger LOG = Logger.getLogger(Crawler.class); + private static DBManagerBasicImpl dbm = new DBManagerBasicImpl(); - public Eye() { + public Crawler() { // setProxy("cmdeviant", 3128, "alexey", "ahGueb1e"); } public List<Place> grubPlaces(String pageSource) { List<String> regExps = new ArrayList<String>(9); regExps.add(".+js$"); regExps.add(".+xml$"); regExps.add(".+swf$"); regExps.add(".+dtd$"); regExps.add(".+jpg$"); regExps.add(".+gif$"); regExps.add(".+bmp$"); regExps.add(".+png$"); //TODO: добавить подждержку ico regExps.add(".+ico$"); List<Place> places = new ArrayList<Place>(); Set<URL> placeUrls = grubURLs(regExps, true); for (URL placeUrl : placeUrls) { - places.add(new Place(placeUrl.toString()));//PENDING + places.add(new Place(placeUrl.toString())); } return places; } public List<Image> grubImages(String pageSource) { List<String> regExps = new ArrayList<String>(4); regExps.add(".+jpg$"); regExps.add(".+gif$"); regExps.add(".+bmp$"); regExps.add(".+png$"); List<Image> images = new ArrayList<Image>(); Set<URL> imageUrls = grubURLs(regExps); for (URL imageUrl : imageUrls) { - try { - images.add(new Image(imageUrl.toString())); - } catch (Exception ex) { - LOG.error("Can't produce image from url " + imageUrl); - } + images.add(new Image(imageUrl.toString())); } return images; } /** * * @param pageSource * @param regExps * @param isExcludeMode если true - url-ки, соответствующие регуляркам * не будут включены в список, иначе - будут включены только те, которые * соответствуют регуляркам * @return */ public Set<URL> grubURLs(List<String> regExps, boolean isExcludeMode) { Set<URL> urls = new HashSet<URL>(); - String urlRegExp = "https?://[-_=+/,.?!&%~:|;#\\w\\d]+";//PENDING + String urlRegExp = "https?://[-_=+/,.?!&%~:|;#\\w\\d]{5,}";//PENDING String[] words = pageSource.split("\\s"); for (String word : words) { word = word.replaceFirst(".*?http", "http"); if (!word.startsWith("http")){ word = word.replaceFirst(".*?href=\"/", "http://" + domain + "/"); word = word.replaceFirst(".*?href='/", "http://" + domain + "/"); word = word.replaceFirst(".*?src=\"/", "http://" + domain + "/"); word = word.replaceFirst(".*?src='/", "http://" + domain + "/"); } String url = findRegexp(word, urlRegExp); if (url != null) { try { url = url.replaceFirst("/$", "");//убираем последний слэшик, чтобы избежать дублирования ссылок urls.add(new URL(url)); } catch (MalformedURLException ex) { LOG.error("Incorrect url: " + url, ex); } } } //Если вызван без регулярок - возвращаем все url if (regExps == null) { return urls; } for (Iterator<URL> url = urls.iterator(); url.hasNext();) { String res = findRegexp(url.next().toString(), regExps); if (isExcludeMode) { if (res != null) { url.remove(); } } else { if (res == null) { url.remove(); } } } return urls; } /** * Возвращает список всех url, найденных в исходнике страницы * @param pageSource * @return */ public Set<URL> grubURLs() { return grubURLs(null, false); } /** * Возвращает список url, найденных в исходнике страницы, соответсвующим регуляркам * @param pageSource * @return */ public Set<URL> grubURLs(List<String> regExps) { return grubURLs(regExps, false); } private static String pageSource = ""; private static String domain = ""; public void run() { ObjectContainer db = dbm.getContainer(); try { Runnable imagesGrubbing = new Runnable() { public void run() { List<Image> images = grubImages(pageSource); if (images.size() > 0) { long t1 = System.currentTimeMillis(); int savedQty = dbm.store(images); long t2 = System.currentTimeMillis() - t1; if (savedQty > 0) LOG.info("---------> Storing new images [" + savedQty + "] done. --> " + t2 + " ms"); } } }; Runnable placesGrubbing = new Runnable() { public void run() { List<Place> places = grubPlaces(pageSource); if (places.size() > 0) { long t1 = System.currentTimeMillis(); int savedQty = dbm.store(places); long t2 = System.currentTimeMillis() - t1; if (savedQty > 0) LOG.info("---------> Storing new places [" + savedQty + "] done. --> " + t2 + " ms"); } } }; Query query = db.query(); query.constrain(Place.class); query.descend("date").orderAscending();//те, что без даты сортируются наверх int placeIdx = 0; ObjectSet<Place> places = query.execute(); LOG.info("Places in db: " + places.size()); for (Place p : places) { try { placeIdx++; LOG.info("[" + placeIdx + "/" + places.size() + "] Seeking in " + p.getUrl()); //Данные для grubURL(); URL u = new URL(p.getUrl()); pageSource = getPageSource(u); domain = u.getHost(); ThreadGroup tg = new ThreadGroup("sources"); new Thread(tg, imagesGrubbing).start(); new Thread(tg, placesGrubbing).start(); //Ждем завершения потоков.. while(tg.activeCount() > 0) Thread.sleep(10); p.setDate(new Date()); db.store(p); } catch (Exception ex) { db.delete(p); LOG.error(ex); } finally { db.commit(); } } } finally { db.close(); } }//seek public static void main(String[] args) throws InterruptedException, MalformedURLException { - if (!hasInetConnection()) { + /*if (!hasInetConnection()) { LOG.error("Inet is unreachable! =("); System.exit(1); - } + }*/ - Eye eye = new Eye(); - dbm.storePlace("http://ya.ru"); + Crawler eye = new Crawler(); +// dbm.store(new Place("http://rambler.ru")); + dbm.store(new Image("http://localhost/points1.png")); + dbm.store(new Image("http://localhost/points2.png")); + dbm.store(new Image("http://localhost/points3.png")); + dbm.store(new Image("http://localhost/points4.png")); + dbm.store(new Image("http://localhost/points5.png")); + dbm.store(new Image("http://localhost/points6.jpg")); + dbm.store(new Image("http://localhost/points7.jpg")); + dbm.store(new Image("http://localhost/points8.jpg")); + dbm.store(new Image("http://localhost/medved1.jpg")); + dbm.store(new Image("http://localhost/medved2.jpg")); + dbm.store(new Image("http://localhost/medved3.jpg")); + dbm.store(new Image("http://localhost/medved4.jpg")); + dbm.store(new Image("http://localhost/medved5.jpg")); + dbm.store(new Image("http://localhost/logo.png")); + dbm.store(new Image("http://localhost/logo2.png")); // eye.watchDb(); - eye.run(); - /*while (true) { +// eye.run(); + /* while (true) { eye.run(); Thread.sleep(1000); }*/ /*URL u = new URL("http://ya.ru"); pageSource = eye.getPageSource(u); domain = u.getHost(); Set<URL> urls = eye.grubURLs(); for (URL url : urls) { System.out.println(url); } System.out.println("size: " + urls.size());*/ } /** * Находит фрагмент строки из source, соответстующий любой регулярке из regs * @param source * @param regs * @return */ private String findRegexp(String source, List<String> regs) { for (String reg : regs) { Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(source.toLowerCase()); if (matcher.find()) { return matcher.group(); } } return null; } /** * Находит фрагмент строки из source, соответстующий регулярке из reg * @param source * @param reg * @return */ private String findRegexp(String source, String reg) { List<String> regs = new ArrayList<String>(1); regs.add(reg); return findRegexp(source, regs); } private String getPageSource(URL url) { StringBuilder response = new StringBuilder(); HttpURLConnection con; try { con = (HttpURLConnection) url.openConnection(); // con.setRequestProperty("Accept-Charset", "cp1251"); con.connect(); Scanner scanner = new Scanner(con.getInputStream()); while (scanner.hasNext()) { response.append(scanner.nextLine()); } con.disconnect(); } catch (Exception ex) { LOG.error("The place is unreachable: " + url); return ""; } return response.toString(); } } diff --git a/src/eye/.svn/text-base/DBManagerEyeImpl.java.svn-base b/src/eye/crawler/.svn/text-base/DBManagerEyeImpl.java.svn-base similarity index 74% rename from src/eye/.svn/text-base/DBManagerEyeImpl.java.svn-base rename to src/eye/crawler/.svn/text-base/DBManagerEyeImpl.java.svn-base index 520063e..787f84c 100644 --- a/src/eye/.svn/text-base/DBManagerEyeImpl.java.svn-base +++ b/src/eye/crawler/.svn/text-base/DBManagerEyeImpl.java.svn-base @@ -1,113 +1,129 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package eye; import com.db4o.ObjectContainer; import com.db4o.ObjectSet; import com.db4o.cs.Db4oClientServer; import db4oserver.AbstractDBManager; import db4oserver.ConfigLoader; import eye.models.Image; import eye.models.Place; +import eye.models.RemoteSource; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; +//import org.apache.log4j.Logger; /** * * @author spr1ng * @version $Id$ */ public class DBManagerEyeImpl extends AbstractDBManager{ private static ConfigLoader conf = ConfigLoader.getInstance(); + //public static final Logger LOG = Logger.getLogger(DBManagerEyeImpl.class); public ObjectContainer getContainer() { return Db4oClientServer.openClient(Db4oClientServer .newClientConfiguration(), conf.getHost(), conf.getPort(), conf.getUser(), conf.getPass()); } public void watchDb() { ObjectContainer db = getContainer(); try { watchDb(db); } finally { db.close(); } } public void watchDb(ObjectContainer db) { ObjectSet objects = db.query().execute(); int places = 0, images = 0; for (Object object : objects) { if (object instanceof Place) { places++; Place p = (Place) object; LOG.info("Place url: " + p.getUrl()); if (p.getDate() != null) { LOG.info("Place data: " + p.getDate()); } } } LOG.info("-------> Total places: " + places); for (Object object : objects) { if (object instanceof Image) { images++; Image i = (Image) object; LOG.info("Image: " + i.getUrl()); if (i.getPoints() != null) { LOG.info("!!!!!!!!!!!!!!!!!!!!!!!Points: " + i.getPoints()); } } } LOG.info("-------> Total images: " + images); LOG.info("Total objects: " + objects.size()); } /** * Сохраняет все объекты списка в базу. Возвращает количество новых * сохраненных объектов * @param objects */ public int store(List objects) { if (objects == null) { - LOG.error("A try to store a null list of objects"); + LOG.severe("A try to store a null list of objects"); return 0; } ObjectContainer db = getContainer(); int qty = 0; try { for (Object o : objects) { if (o != null) { //Если такого объекта еще нет в базе if (!isItemStored(o)) { db.store(o); qty++; } //else LOG.error("A try to store a duplicate object"); //DELME: - } else LOG.error("A try to store a null object"); + } else LOG.severe("A try to store a null object"); } } finally { db.close(); } return qty; } - /** Сохраняет место поиска глаза */ - public void storePlace(String firstPlace) { - //Инициализируем первое место поиска + /** Сохраняет удаленный источник в БД */ + public void store(RemoteSource rs) { try { - new URL(firstPlace); + new URL(rs.getUrl()); } catch (MalformedURLException ex) { - LOG.error("Can't reach target: " + firstPlace, ex); + LOG.severe("Can't reach target: " + rs.getUrl()); } - List<Place> places = new ArrayList<Place>(1); - places.add(new Place(firstPlace)); - store(places); + List<RemoteSource> sources = new ArrayList<RemoteSource>(1); + sources.add(rs); + store(sources); + } + + /** Retrieves all images from DB */ + public List<Image> getAllImages(){//PENDING: нельзя здесь закрывать. понять почему!! + ObjectContainer db = getContainer(); + try { + return db.query(Image.class); + }catch(Exception e){ + e.printStackTrace(); + return null; + } /*finally { + db.close(); + }*/ + } } diff --git a/src/eye/.svn/text-base/Eye.java.svn-base b/src/eye/crawler/.svn/text-base/Eye.java.svn-base similarity index 89% rename from src/eye/.svn/text-base/Eye.java.svn-base rename to src/eye/crawler/.svn/text-base/Eye.java.svn-base index 46370a2..db5d0cf 100644 --- a/src/eye/.svn/text-base/Eye.java.svn-base +++ b/src/eye/crawler/.svn/text-base/Eye.java.svn-base @@ -1,307 +1,305 @@ package eye; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Date; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.net.URL; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.util.HashSet; import java.util.Set; import org.apache.log4j.Logger; import com.db4o.ObjectContainer; import com.db4o.ObjectSet; import com.db4o.query.Query; import eye.models.Image; import eye.models.Place; import static eye.net.InetUtils.*; /** * The Eye - yet another crawler ;) * @author gpdribbler, spr1ng * @version $Id$ */ public class Eye { private static final Logger LOG = Logger.getLogger(Eye.class); private static DBManagerEyeImpl dbm = new DBManagerEyeImpl(); public Eye() { // setProxy("cmdeviant", 3128, "alexey", "ahGueb1e"); } - private static final int PORT = 4488; - private static final String USER = "db4o"; - private static final String PASS = "db4o"; - - - - /*public static ObjectContainer getConnection() { - return Db4oClientServer.openClient(Db4oClientServer - .newClientConfiguration(), "localhost", PORT, USER, PASS); - }*/ - public List<Place> grubPlaces(String pageSource) { List<String> regExps = new ArrayList<String>(9); regExps.add(".+js$"); regExps.add(".+xml$"); regExps.add(".+swf$"); regExps.add(".+dtd$"); regExps.add(".+jpg$"); regExps.add(".+gif$"); regExps.add(".+bmp$"); regExps.add(".+png$"); //TODO: добавить подждержку ico regExps.add(".+ico$"); List<Place> places = new ArrayList<Place>(); Set<URL> placeUrls = grubURLs(regExps, true); for (URL placeUrl : placeUrls) { - places.add(new Place(placeUrl.toString()));//PENDING + places.add(new Place(placeUrl.toString())); } return places; } public List<Image> grubImages(String pageSource) { List<String> regExps = new ArrayList<String>(4); regExps.add(".+jpg$"); regExps.add(".+gif$"); regExps.add(".+bmp$"); regExps.add(".+png$"); List<Image> images = new ArrayList<Image>(); Set<URL> imageUrls = grubURLs(regExps); for (URL imageUrl : imageUrls) { - try { - images.add(new Image(imageUrl.toString())); - } catch (Exception ex) { - LOG.error("Can't produce image from url " + imageUrl); - } + images.add(new Image(imageUrl.toString())); } return images; } /** * * @param pageSource * @param regExps * @param isExcludeMode если true - url-ки, соответствующие регуляркам * не будут включены в список, иначе - будут включены только те, которые * соответствуют регуляркам * @return */ public Set<URL> grubURLs(List<String> regExps, boolean isExcludeMode) { Set<URL> urls = new HashSet<URL>(); - String urlRegExp = "https?://[-_=+/,.?!&%~:|;#\\w\\d]+";//PENDING + String urlRegExp = "https?://[-_=+/,.?!&%~:|;#\\w\\d]{5,}";//PENDING String[] words = pageSource.split("\\s"); for (String word : words) { word = word.replaceFirst(".*?http", "http"); if (!word.startsWith("http")){ word = word.replaceFirst(".*?href=\"/", "http://" + domain + "/"); word = word.replaceFirst(".*?href='/", "http://" + domain + "/"); word = word.replaceFirst(".*?src=\"/", "http://" + domain + "/"); word = word.replaceFirst(".*?src='/", "http://" + domain + "/"); } String url = findRegexp(word, urlRegExp); if (url != null) { try { url = url.replaceFirst("/$", "");//убираем последний слэшик, чтобы избежать дублирования ссылок urls.add(new URL(url)); } catch (MalformedURLException ex) { LOG.error("Incorrect url: " + url, ex); } } } //Если вызван без регулярок - возвращаем все url if (regExps == null) { return urls; } for (Iterator<URL> url = urls.iterator(); url.hasNext();) { String res = findRegexp(url.next().toString(), regExps); if (isExcludeMode) { if (res != null) { url.remove(); } } else { if (res == null) { url.remove(); } } } return urls; } /** * Возвращает список всех url, найденных в исходнике страницы * @param pageSource * @return */ public Set<URL> grubURLs() { return grubURLs(null, false); } /** * Возвращает список url, найденных в исходнике страницы, соответсвующим регуляркам * @param pageSource * @return */ public Set<URL> grubURLs(List<String> regExps) { return grubURLs(regExps, false); } private static String pageSource = ""; private static String domain = ""; public void run() { ObjectContainer db = dbm.getContainer(); try { Runnable imagesGrubbing = new Runnable() { public void run() { List<Image> images = grubImages(pageSource); if (images.size() > 0) { long t1 = System.currentTimeMillis(); int savedQty = dbm.store(images); long t2 = System.currentTimeMillis() - t1; if (savedQty > 0) LOG.info("---------> Storing new images [" + savedQty + "] done. --> " + t2 + " ms"); } } }; Runnable placesGrubbing = new Runnable() { public void run() { List<Place> places = grubPlaces(pageSource); if (places.size() > 0) { long t1 = System.currentTimeMillis(); int savedQty = dbm.store(places); long t2 = System.currentTimeMillis() - t1; if (savedQty > 0) LOG.info("---------> Storing new places [" + savedQty + "] done. --> " + t2 + " ms"); } } }; Query query = db.query(); query.constrain(Place.class); query.descend("date").orderAscending();//те, что без даты сортируются наверх int placeIdx = 0; ObjectSet<Place> places = query.execute(); LOG.info("Places in db: " + places.size()); for (Place p : places) { try { placeIdx++; LOG.info("[" + placeIdx + "/" + places.size() + "] Seeking in " + p.getUrl()); //Данные для grubURL(); URL u = new URL(p.getUrl()); pageSource = getPageSource(u); domain = u.getHost(); ThreadGroup tg = new ThreadGroup("sources"); new Thread(tg, imagesGrubbing).start(); new Thread(tg, placesGrubbing).start(); //Ждем завершения потоков.. while(tg.activeCount() > 0) Thread.sleep(10); p.setDate(new Date()); db.store(p); } catch (Exception ex) { db.delete(p); LOG.error(ex); } finally { db.commit(); } } } finally { db.close(); } }//seek public static void main(String[] args) throws InterruptedException, MalformedURLException { - if (!hasInetConnection()) { + /*if (!hasInetConnection()) { LOG.error("Inet is unreachable! =("); System.exit(1); - } + }*/ Eye eye = new Eye(); - dbm.storePlace("http://ya.ru"); +// dbm.store(new Place("http://rambler.ru")); + dbm.store(new Image("http://localhost/points1.png")); + dbm.store(new Image("http://localhost/points2.png")); + dbm.store(new Image("http://localhost/points3.png")); + dbm.store(new Image("http://localhost/points4.png")); + dbm.store(new Image("http://localhost/points5.png")); + dbm.store(new Image("http://localhost/points6.jpg")); + dbm.store(new Image("http://localhost/points7.jpg")); + dbm.store(new Image("http://localhost/points8.jpg")); + dbm.store(new Image("http://localhost/medved1.jpg")); + dbm.store(new Image("http://localhost/medved2.jpg")); + dbm.store(new Image("http://localhost/medved3.jpg")); + dbm.store(new Image("http://localhost/logo.png")); + dbm.store(new Image("http://localhost/logo2.png")); // eye.watchDb(); - eye.run(); - /*while (true) { +// eye.run(); + /* while (true) { eye.run(); Thread.sleep(1000); }*/ /*URL u = new URL("http://ya.ru"); pageSource = eye.getPageSource(u); domain = u.getHost(); Set<URL> urls = eye.grubURLs(); for (URL url : urls) { System.out.println(url); } System.out.println("size: " + urls.size());*/ } /** * Находит фрагмент строки из source, соответстующий любой регулярке из regs * @param source * @param regs * @return */ private String findRegexp(String source, List<String> regs) { for (String reg : regs) { Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(source.toLowerCase()); if (matcher.find()) { return matcher.group(); } } return null; } /** * Находит фрагмент строки из source, соответстующий регулярке из reg * @param source * @param reg * @return */ private String findRegexp(String source, String reg) { List<String> regs = new ArrayList<String>(1); regs.add(reg); return findRegexp(source, regs); } private String getPageSource(URL url) { StringBuilder response = new StringBuilder(); HttpURLConnection con; try { con = (HttpURLConnection) url.openConnection(); // con.setRequestProperty("Accept-Charset", "cp1251"); con.connect(); Scanner scanner = new Scanner(con.getInputStream()); while (scanner.hasNext()) { response.append(scanner.nextLine()); } con.disconnect(); } catch (Exception ex) { LOG.error("The place is unreachable: " + url); return ""; } return response.toString(); } } diff --git a/src/eye/crawler/Crawler.java b/src/eye/crawler/Crawler.java new file mode 100644 index 0000000..fcd2f5a --- /dev/null +++ b/src/eye/crawler/Crawler.java @@ -0,0 +1,307 @@ +package eye.crawler; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Date; +import java.util.Scanner; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.net.URL; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.util.HashSet; +import java.util.Set; +import org.apache.log4j.Logger; +import com.db4o.ObjectContainer; +import com.db4o.ObjectSet; +import com.db4o.query.Query; + +import eye.core.model.Image; +import eye.core.model.Place; +import eye.server.manager.impl.DBManagerBasicImpl; + +/** + * The Crawler - yet another crawler ;) + * @author gpdribbler, spr1ng + * @version $Id: Crawler.java 62 2010-07-08 03:44:15Z spr1ng $ + */ +public class Crawler { + private static final Logger LOG = Logger.getLogger(Crawler.class); + private static DBManagerBasicImpl dbm = new DBManagerBasicImpl(); + + public Crawler() { +// setProxy("cmdeviant", 3128, "alexey", "ahGueb1e"); + } + + public List<Place> grubPlaces(String pageSource) { + List<String> regExps = new ArrayList<String>(9); + regExps.add(".+js$"); + regExps.add(".+xml$"); + regExps.add(".+swf$"); + regExps.add(".+dtd$"); + regExps.add(".+jpg$"); + regExps.add(".+gif$"); + regExps.add(".+bmp$"); + regExps.add(".+png$"); + //TODO: добавить подждержку ico + regExps.add(".+ico$"); + + List<Place> places = new ArrayList<Place>(); + Set<URL> placeUrls = grubURLs(regExps, true); + for (URL placeUrl : placeUrls) { + places.add(new Place(placeUrl.toString())); + } + + return places; + } + + public List<Image> grubImages(String pageSource) { + List<String> regExps = new ArrayList<String>(4); + regExps.add(".+jpg$"); + regExps.add(".+gif$"); + regExps.add(".+bmp$"); + regExps.add(".+png$"); + + List<Image> images = new ArrayList<Image>(); + Set<URL> imageUrls = grubURLs(regExps); + for (URL imageUrl : imageUrls) { + images.add(new Image(imageUrl.toString())); + } + + return images; + } + + /** + * + * @param pageSource + * @param regExps + * @param isExcludeMode если true - url-ки, соответствующие регуляркам + * не будут включены в список, иначе - будут включены только те, которые + * соответствуют регуляркам + * @return + */ + public Set<URL> grubURLs(List<String> regExps, boolean isExcludeMode) { + Set<URL> urls = new HashSet<URL>(); + String urlRegExp = "https?://[-_=+/,.?!&%~:|;#\\w\\d]{5,}";//PENDING + + String[] words = pageSource.split("\\s"); + for (String word : words) { + word = word.replaceFirst(".*?http", "http"); + if (!word.startsWith("http")){ + word = word.replaceFirst(".*?href=\"/", "http://" + domain + "/"); + word = word.replaceFirst(".*?href='/", "http://" + domain + "/"); + word = word.replaceFirst(".*?src=\"/", "http://" + domain + "/"); + word = word.replaceFirst(".*?src='/", "http://" + domain + "/"); + } + String url = findRegexp(word, urlRegExp); + if (url != null) { + try { + url = url.replaceFirst("/$", "");//убираем последний слэшик, чтобы избежать дублирования ссылок + urls.add(new URL(url)); + } catch (MalformedURLException ex) { + LOG.error("Incorrect url: " + url, ex); + } + } + } + //Если вызван без регулярок - возвращаем все url + if (regExps == null) { + return urls; + } + for (Iterator<URL> url = urls.iterator(); url.hasNext();) { + String res = findRegexp(url.next().toString(), regExps); + if (isExcludeMode) { + if (res != null) { + url.remove(); + } + } else { + if (res == null) { + url.remove(); + } + } + } + return urls; + } + + /** + * Возвращает список всех url, найденных в исходнике страницы + * @param pageSource + * @return + */ + public Set<URL> grubURLs() { + return grubURLs(null, false); + } + + /** + * Возвращает список url, найденных в исходнике страницы, соответсвующим регуляркам + * @param pageSource + * @return + */ + public Set<URL> grubURLs(List<String> regExps) { + return grubURLs(regExps, false); + } + + private static String pageSource = ""; + private static String domain = ""; + public void run() { + ObjectContainer db = dbm.getContainer(); + try { + + Runnable imagesGrubbing = new Runnable() { + public void run() { + List<Image> images = grubImages(pageSource); + if (images.size() > 0) { + long t1 = System.currentTimeMillis(); + int savedQty = dbm.store(images); + long t2 = System.currentTimeMillis() - t1; + if (savedQty > 0) + LOG.info("---------> Storing new images [" + savedQty + "] done. --> " + t2 + " ms"); + } + } + }; + + Runnable placesGrubbing = new Runnable() { + public void run() { + List<Place> places = grubPlaces(pageSource); + if (places.size() > 0) { + long t1 = System.currentTimeMillis(); + int savedQty = dbm.store(places); + long t2 = System.currentTimeMillis() - t1; + if (savedQty > 0) + LOG.info("---------> Storing new places [" + savedQty + "] done. --> " + t2 + " ms"); + } + } + }; + + Query query = db.query(); + query.constrain(Place.class); + query.descend("date").orderAscending();//те, что без даты сортируются наверх + + int placeIdx = 0; + ObjectSet<Place> places = query.execute(); + LOG.info("Places in db: " + places.size()); + + for (Place p : places) { + try { + placeIdx++; + LOG.info("[" + placeIdx + "/" + places.size() + "] Seeking in " + p.getUrl()); + //Данные для grubURL(); + URL u = new URL(p.getUrl()); + pageSource = getPageSource(u); + domain = u.getHost(); + + ThreadGroup tg = new ThreadGroup("sources"); + new Thread(tg, imagesGrubbing).start(); + new Thread(tg, placesGrubbing).start(); + + //Ждем завершения потоков.. + while(tg.activeCount() > 0) Thread.sleep(10); + + p.setDate(new Date()); + db.store(p); + } catch (Exception ex) { + db.delete(p); + LOG.error(ex); + } finally { + db.commit(); + } + } + } finally { + db.close(); + } + + }//seek + + + + public static void main(String[] args) throws InterruptedException, MalformedURLException { + /*if (!hasInetConnection()) { + LOG.error("Inet is unreachable! =("); + System.exit(1); + }*/ + + Crawler eye = new Crawler(); +// dbm.store(new Place("http://rambler.ru")); + dbm.store(new Image("http://localhost/points1.png")); + dbm.store(new Image("http://localhost/points2.png")); + dbm.store(new Image("http://localhost/points3.png")); + dbm.store(new Image("http://localhost/points4.png")); + dbm.store(new Image("http://localhost/points5.png")); + dbm.store(new Image("http://localhost/points6.jpg")); + dbm.store(new Image("http://localhost/points7.jpg")); + dbm.store(new Image("http://localhost/points8.jpg")); + dbm.store(new Image("http://localhost/medved1.jpg")); + dbm.store(new Image("http://localhost/medved2.jpg")); + dbm.store(new Image("http://localhost/medved3.jpg")); + dbm.store(new Image("http://localhost/medved4.jpg")); + dbm.store(new Image("http://localhost/medved5.jpg")); + dbm.store(new Image("http://localhost/logo.png")); + dbm.store(new Image("http://localhost/logo2.png")); +// eye.watchDb(); +// eye.run(); + /* while (true) { + eye.run(); + Thread.sleep(1000); + }*/ + /*URL u = new URL("http://ya.ru"); + pageSource = eye.getPageSource(u); + domain = u.getHost(); + Set<URL> urls = eye.grubURLs(); + for (URL url : urls) { + System.out.println(url); + } + System.out.println("size: " + urls.size());*/ + } + + /** + * Находит фрагмент строки из source, соответстующий любой регулярке из regs + * @param source + * @param regs + * @return + */ + private String findRegexp(String source, List<String> regs) { + for (String reg : regs) { + Pattern pattern = Pattern.compile(reg); + Matcher matcher = pattern.matcher(source.toLowerCase()); + if (matcher.find()) { + return matcher.group(); + } + } + return null; + } + + /** + * Находит фрагмент строки из source, соответстующий регулярке из reg + * @param source + * @param reg + * @return + */ + private String findRegexp(String source, String reg) { + List<String> regs = new ArrayList<String>(1); + regs.add(reg); + return findRegexp(source, regs); + } + + private String getPageSource(URL url) { + StringBuilder response = new StringBuilder(); + + HttpURLConnection con; + try { + con = (HttpURLConnection) url.openConnection(); +// con.setRequestProperty("Accept-Charset", "cp1251"); + con.connect(); + Scanner scanner = new Scanner(con.getInputStream()); + while (scanner.hasNext()) { + response.append(scanner.nextLine()); + } + + con.disconnect(); + } catch (Exception ex) { + LOG.error("The place is unreachable: " + url); + return ""; + } + + return response.toString(); + } + +} diff --git a/src/eye/models/.svn/entries b/src/eye/models/.svn/entries index b15fe29..09776b0 100644 --- a/src/eye/models/.svn/entries +++ b/src/eye/models/.svn/entries @@ -1,164 +1,37 @@ 10 dir -19 +70 svn://localhost/spr1ngsvn/TheEye/Eye/src/eye/models svn://localhost/spr1ngsvn/TheEye +delete - -2010-06-30T03:16:43.109433Z -19 -stream - - - - - - - - - - - - - - -8763ed6d-9318-4032-b958-c511fcb819a9 - -Image.java -file -24 - - - -2010-06-30T07:43:46.027067Z -665663343142c8b25db9fd2bffa0078a -2010-06-30T07:43:45.867637Z -24 -spr1ng -has-props - - - - - - - - - - - - - - - - - - - - -1388 - -Place.java -file -24 - - - -2010-06-30T07:43:46.027067Z -f60f503b66e1c6d23ef0187d37bc7ca9 -2010-06-30T07:43:45.867637Z -24 -spr1ng -has-props - - - - - - - - - - - - - - - - - - - - -800 - -Point.java -file -24 - - - -2010-06-30T07:43:46.027067Z -6eeba21d167396d9c9f91a2f1e7f6311 -2010-06-30T07:43:45.867637Z -24 +2010-07-08T03:46:39.872166Z +67 spr1ng -has-props - - - - - - -2064 - -RemoteSource.java -file -24 - - - -2010-06-30T07:43:46.031066Z -fd8ca6805676363a6121820c667a3e3c -2010-06-30T07:43:45.867637Z -24 -spr1ng -has-props - - - - - - - - - - - - +8763ed6d-9318-4032-b958-c511fcb819a9 -322 +((conflict result dir update deleted edited (version svn://localhost/spr1ngsvn/TheEye 2 52 Eye/src/eye/models/result dir) (version svn://localhost/spr1ngsvn/TheEye 2 55 Eye/src/eye/models/result none))) diff --git a/src/eye/models/.svn/prop-base/Image.java.svn-base b/src/eye/models/.svn/prop-base/Image.java.svn-base deleted file mode 100644 index 92c8ad7..0000000 --- a/src/eye/models/.svn/prop-base/Image.java.svn-base +++ /dev/null @@ -1,5 +0,0 @@ -K 12 -svn:keywords -V 2 -Id -END diff --git a/src/eye/models/.svn/prop-base/Place.java.svn-base b/src/eye/models/.svn/prop-base/Place.java.svn-base deleted file mode 100644 index 92c8ad7..0000000 --- a/src/eye/models/.svn/prop-base/Place.java.svn-base +++ /dev/null @@ -1,5 +0,0 @@ -K 12 -svn:keywords -V 2 -Id -END diff --git a/src/eye/models/.svn/prop-base/Point.java.svn-base b/src/eye/models/.svn/prop-base/Point.java.svn-base deleted file mode 100644 index 92c8ad7..0000000 --- a/src/eye/models/.svn/prop-base/Point.java.svn-base +++ /dev/null @@ -1,5 +0,0 @@ -K 12 -svn:keywords -V 2 -Id -END diff --git a/src/eye/models/.svn/prop-base/RemoteSource.java.svn-base b/src/eye/models/.svn/prop-base/RemoteSource.java.svn-base deleted file mode 100644 index 92c8ad7..0000000 --- a/src/eye/models/.svn/prop-base/RemoteSource.java.svn-base +++ /dev/null @@ -1,5 +0,0 @@ -K 12 -svn:keywords -V 2 -Id -END diff --git a/src/eye/models/.svn/text-base/Image.java.svn-base b/src/eye/models/.svn/text-base/Image.java.svn-base deleted file mode 100644 index e402c14..0000000 --- a/src/eye/models/.svn/text-base/Image.java.svn-base +++ /dev/null @@ -1,65 +0,0 @@ -package eye.models; - -import java.util.Iterator; -import java.util.List; - -/** - * - * @author gpdribbler, spr1ng, stream - * @version $Id$ - */ -public class Image implements RemoteSource{ - - private String url; - private List<Point> points; - - public Image() { - } - - public Image(String url) { - this.url = url; - } - - public Image(String url, List<Point> points) { - this.url = url; - this.points = points; - } - - public List<Point> getPoints() { - return points; - } - - public void setPoints(List<Point> points) { - this.points = points; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - @Override - public String toString() { - String result = "";//url.toString(); - result += ": " + points.size() + " points"; - return result; - } - - //TODO: реализовать - public int compareTo(Image image) { - int result = 0; - for (Iterator<Point> it = points.iterator(); it.hasNext();) - for (Iterator<Point> it1 = image.getPoints().iterator(); it.hasNext();) - result += it.next().compareTo(it1.next()); - return result; - } - - public boolean hasMetaData(){ - if (points == null) return false; - return true; - } - -} diff --git a/src/eye/models/.svn/text-base/Place.java.svn-base b/src/eye/models/.svn/text-base/Place.java.svn-base deleted file mode 100644 index 98d9ac7..0000000 --- a/src/eye/models/.svn/text-base/Place.java.svn-base +++ /dev/null @@ -1,48 +0,0 @@ -package eye.models; - -import java.util.Date; - -/** - * - * @author gpdribbler, spr1ng, stream - * @version $Id$ - */ -public class Place implements RemoteSource{ - - private String url; - private Date date; - - public Place() { - } - - public Place(String url, Date date) { - this.url = url; - this.date = date; - } - - public Place(String url) { - this.url = url; - } - - public Date getDate() { - return date; - } - - public void setDate(Date date) { - this.date = date; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - @Override - public String toString() { - return url + " " + String.valueOf(date); - } - -} diff --git a/src/eye/models/.svn/text-base/Point.java.svn-base b/src/eye/models/.svn/text-base/Point.java.svn-base deleted file mode 100644 index 4c3c89c..0000000 --- a/src/eye/models/.svn/text-base/Point.java.svn-base +++ /dev/null @@ -1,86 +0,0 @@ -package eye.models; - -import java.awt.image.BufferedImage; - -/** - * - * @author gpdribbler - * @version $Id$ - */ -public class Point { - - private int x; - private int y; - private BufferedImage image; - - public Point() { - } - - public Point(int x, int y, BufferedImage image) { - this.x = x; - this.y = y; - this.image = image; - } - - //TODO: вычислять расстояние с поправкой на рубежность точки? - public int compareTo(Point p) { - int result = (x - p.getX()) * (x - p.getX()); - result += (y - p.getY()) * (y - p.getY()); - return (int) Math.sqrt(result); - } - - public boolean isBorder(int limit) { - int diff = 0; - for(int i = -1; i <= 1; i++) - for(int j = -1; j <= 1; j++) - diff += getRGBDifference(new Point(x+i, y+j, image)); - diff /= 8; - if(diff > limit) { - return true; - } else { - return false; - } - }//isBorderPixel - - public int getRGBDifference(Point point) { - int rgb1 = image.getRGB(x, y); - int rgb2 = image.getRGB(point.getX(), point.getY()); - - int red1 = (rgb1 & 0x00ff0000) >> 16; - int green1 = (rgb1 & 0x0000ff00) >> 8; - int blue1 = (rgb1 & 0x000000ff); - - int red2 = (rgb2 & 0x00ff0000) >> 16; - int green2 = (rgb2 & 0x0000ff00) >> 8; - int blue2 = (rgb2 & 0x000000ff); - - return (int) Math.sqrt( (red1 - red2)*(red1 - red2) + (green1 - green2) - * (green1 - green2) + (blue1 - blue2) * (blue1 - blue2) ); - }//getDifference - - - public int getX() { - return x; - } - - public void setX(int x) { - this.x = x; - } - - public int getY() { - return y; - } - - public void setY(int y) { - this.y = y; - } - - public BufferedImage getImage() { - return image; - } - - public void setImage(BufferedImage image) { - this.image = image; - } - -} diff --git a/src/eye/models/.svn/text-base/RemoteSource.java.svn-base b/src/eye/models/.svn/text-base/RemoteSource.java.svn-base deleted file mode 100644 index 61f1e34..0000000 --- a/src/eye/models/.svn/text-base/RemoteSource.java.svn-base +++ /dev/null @@ -1,17 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package eye.models; - -/** - * - * @author stream - * @version $Id$ - */ -public interface RemoteSource { - - public String getUrl(); - public void setUrl(String url); - -} diff --git a/src/eye/models/.svn/text-base/SearchResult.java.svn-base b/src/eye/models/.svn/text-base/SearchResult.java.svn-base new file mode 100644 index 0000000..6ee12d0 --- /dev/null +++ b/src/eye/models/.svn/text-base/SearchResult.java.svn-base @@ -0,0 +1,49 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package eye.models; + +import java.util.List; + +/** + * + * @author spr1ng + * @version $Id$ + */ +public class SearchResult { + + private Image userImage; + private List<Image> images; + + public SearchResult(Image userImage, List<Image> images) { + this.userImage = userImage; + this.images = images; + } + + public SearchResult(List<Image> images) { + this.images = images; + } + + public Image getUserImage() { + return userImage; + } + + public void setUserImage(Image userImage) { + this.userImage = userImage; + } + + public List<Image> getImages() { + return images; + } + + public void setImages(List<Image> images) { + this.images = images; + } + + public int totalImages(){ + return images.size(); + } + +} diff --git a/src/eye/models/Image.java b/src/eye/models/Image.java deleted file mode 100644 index df5f28d..0000000 --- a/src/eye/models/Image.java +++ /dev/null @@ -1,65 +0,0 @@ -package eye.models; - -import java.util.Iterator; -import java.util.List; - -/** - * - * @author gpdribbler, spr1ng, stream - * @version $Id: Image.java 24 2010-06-30 07:43:45Z spr1ng $ - */ -public class Image implements RemoteSource{ - - private String url; - private List<Point> points; - - public Image() { - } - - public Image(String url) { - this.url = url; - } - - public Image(String url, List<Point> points) { - this.url = url; - this.points = points; - } - - public List<Point> getPoints() { - return points; - } - - public void setPoints(List<Point> points) { - this.points = points; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - @Override - public String toString() { - String result = "";//url.toString(); - result += ": " + points.size() + " points"; - return result; - } - - //TODO: реализовать - public int compareTo(Image image) { - int result = 0; - for (Iterator<Point> it = points.iterator(); it.hasNext();) - for (Iterator<Point> it1 = image.getPoints().iterator(); it.hasNext();) - result += it.next().compareTo(it1.next()); - return result; - } - - public boolean hasMetaData(){ - if (points == null) return false; - return true; - } - -} diff --git a/src/eye/models/Place.java b/src/eye/models/Place.java deleted file mode 100644 index 17f9140..0000000 --- a/src/eye/models/Place.java +++ /dev/null @@ -1,48 +0,0 @@ -package eye.models; - -import java.util.Date; - -/** - * - * @author gpdribbler, spr1ng, stream - * @version $Id: Place.java 24 2010-06-30 07:43:45Z spr1ng $ - */ -public class Place implements RemoteSource{ - - private String url; - private Date date; - - public Place() { - } - - public Place(String url, Date date) { - this.url = url; - this.date = date; - } - - public Place(String url) { - this.url = url; - } - - public Date getDate() { - return date; - } - - public void setDate(Date date) { - this.date = date; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - @Override - public String toString() { - return url + " " + String.valueOf(date); - } - -} diff --git a/src/eye/models/Point.java b/src/eye/models/Point.java deleted file mode 100644 index cd99804..0000000 --- a/src/eye/models/Point.java +++ /dev/null @@ -1,86 +0,0 @@ -package eye.models; - -import java.awt.image.BufferedImage; - -/** - * - * @author gpdribbler - * @version $Id: Point.java 24 2010-06-30 07:43:45Z spr1ng $ - */ -public class Point { - - private int x; - private int y; - private BufferedImage image; - - public Point() { - } - - public Point(int x, int y, BufferedImage image) { - this.x = x; - this.y = y; - this.image = image; - } - - //TODO: вычислять расстояние с поправкой на рубежность точки? - public int compareTo(Point p) { - int result = (x - p.getX()) * (x - p.getX()); - result += (y - p.getY()) * (y - p.getY()); - return (int) Math.sqrt(result); - } - - public boolean isBorder(int limit) { - int diff = 0; - for(int i = -1; i <= 1; i++) - for(int j = -1; j <= 1; j++) - diff += getRGBDifference(new Point(x+i, y+j, image)); - diff /= 8; - if(diff > limit) { - return true; - } else { - return false; - } - }//isBorderPixel - - public int getRGBDifference(Point point) { - int rgb1 = image.getRGB(x, y); - int rgb2 = image.getRGB(point.getX(), point.getY()); - - int red1 = (rgb1 & 0x00ff0000) >> 16; - int green1 = (rgb1 & 0x0000ff00) >> 8; - int blue1 = (rgb1 & 0x000000ff); - - int red2 = (rgb2 & 0x00ff0000) >> 16; - int green2 = (rgb2 & 0x0000ff00) >> 8; - int blue2 = (rgb2 & 0x000000ff); - - return (int) Math.sqrt( (red1 - red2)*(red1 - red2) + (green1 - green2) - * (green1 - green2) + (blue1 - blue2) * (blue1 - blue2) ); - }//getDifference - - - public int getX() { - return x; - } - - public void setX(int x) { - this.x = x; - } - - public int getY() { - return y; - } - - public void setY(int y) { - this.y = y; - } - - public BufferedImage getImage() { - return image; - } - - public void setImage(BufferedImage image) { - this.image = image; - } - -} diff --git a/src/eye/models/RemoteSource.java b/src/eye/models/RemoteSource.java deleted file mode 100644 index b65b159..0000000 --- a/src/eye/models/RemoteSource.java +++ /dev/null @@ -1,17 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package eye.models; - -/** - * - * @author stream - * @version $Id: RemoteSource.java 24 2010-06-30 07:43:45Z spr1ng $ - */ -public interface RemoteSource { - - public String getUrl(); - public void setUrl(String url); - -} diff --git a/src/eye/net/.svn/entries b/src/eye/net/.svn/entries index ad4083f..947e41e 100644 --- a/src/eye/net/.svn/entries +++ b/src/eye/net/.svn/entries @@ -1,62 +1,28 @@ 10 dir -28 +70 svn://localhost/spr1ngsvn/TheEye/Eye/src/eye/net svn://localhost/spr1ngsvn/TheEye +delete - -2010-07-01T05:35:24.601857Z -28 +2010-07-08T03:46:20.521097Z +63 spr1ng 8763ed6d-9318-4032-b958-c511fcb819a9 -InetUtils.java -file - - - - -2010-07-01T05:00:24.026572Z -e7f202cff15cf5967def79b7b9e210de -2010-07-01T05:35:24.601857Z -28 -spr1ng - - - - - - - - - - - - - - - - - - - - - -1910 - diff --git a/src/eye/net/.svn/text-base/InetUtils.java.svn-base b/src/eye/net/.svn/text-base/InetUtils.java.svn-base deleted file mode 100644 index 787c29e..0000000 --- a/src/eye/net/.svn/text-base/InetUtils.java.svn-base +++ /dev/null @@ -1,68 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package eye.net; - -import java.net.Authenticator; -import java.net.PasswordAuthentication; -import java.net.URL; -import java.net.URLConnection; -import org.apache.log4j.Logger; - -/** - * - * @author spr1ng - */ -public class InetUtils { - - private final static Logger LOG = Logger.getLogger(InetUtils.class); - - /** - * @param host - * @param port - * @param login - * @param pass - */ - public void setProxy(String host, Integer port, final String login, final String pass) { - System.setProperty("http.proxyHost", host); - System.setProperty("http.proxyPort", port.toString()); - Authenticator.setDefault(new Authenticator() { - @Override - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(login, pass.toCharArray()); - } - }); - } - /** - * Определяет, доступен ли удаленный ресурс - * @param url - * @param timeout - * @return - */ - public static boolean isReachable(String url, int timeout){ - try { - URL u = new URL(url); - URLConnection conn = u.openConnection(); - conn.setConnectTimeout(timeout); - conn.connect(); - } catch (Exception ex) { - LOG.error(ex.getMessage()); - return false; - } - return true; - } - - /** Определяет, доступен ли удаленный ресурс */ - public static boolean isReachable(String url){ - return isReachable(url, 500); - } - - /** Полезен при определении, есть ли у модуля доступ к интернет */ - public static boolean hasInetConnection(){ - return isReachable("http://ya.ru", 3000); - } - - -} diff --git a/src/eye/net/InetUtils.java b/src/eye/net/InetUtils.java deleted file mode 100644 index 787c29e..0000000 --- a/src/eye/net/InetUtils.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package eye.net; - -import java.net.Authenticator; -import java.net.PasswordAuthentication; -import java.net.URL; -import java.net.URLConnection; -import org.apache.log4j.Logger; - -/** - * - * @author spr1ng - */ -public class InetUtils { - - private final static Logger LOG = Logger.getLogger(InetUtils.class); - - /** - * @param host - * @param port - * @param login - * @param pass - */ - public void setProxy(String host, Integer port, final String login, final String pass) { - System.setProperty("http.proxyHost", host); - System.setProperty("http.proxyPort", port.toString()); - Authenticator.setDefault(new Authenticator() { - @Override - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(login, pass.toCharArray()); - } - }); - } - /** - * Определяет, доступен ли удаленный ресурс - * @param url - * @param timeout - * @return - */ - public static boolean isReachable(String url, int timeout){ - try { - URL u = new URL(url); - URLConnection conn = u.openConnection(); - conn.setConnectTimeout(timeout); - conn.connect(); - } catch (Exception ex) { - LOG.error(ex.getMessage()); - return false; - } - return true; - } - - /** Определяет, доступен ли удаленный ресурс */ - public static boolean isReachable(String url){ - return isReachable(url, 500); - } - - /** Полезен при определении, есть ли у модуля доступ к интернет */ - public static boolean hasInetConnection(){ - return isReachable("http://ya.ru", 3000); - } - - -} diff --git a/src/log4j.xml b/src/log4j.xml new file mode 100644 index 0000000..9a584ff --- /dev/null +++ b/src/log4j.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> + + <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> + + <appender name="console" class="org.apache.log4j.ConsoleAppender"> + <param name="Target" value="System.out"/> + <layout class="org.apache.log4j.PatternLayout"> + <param name="ConversionPattern" value="%p %c: %m%n"/> + </layout> + </appender> + <!--Корневой logger--> + <root> + <priority value ="debug" /> + <appender-ref ref="console" /> + </root> + + </log4j:configuration> \ No newline at end of file
spr1ng/Crawler
0d6bdf1d87c605749cc366da9e92886ef35e0040
Вдогонку! ;)
diff --git a/.svn/dir-prop-base b/.svn/dir-prop-base new file mode 100644 index 0000000..bd19930 --- /dev/null +++ b/.svn/dir-prop-base @@ -0,0 +1,6 @@ +K 10 +svn:ignore +V 6 +build + +END diff --git a/.svn/entries b/.svn/entries new file mode 100644 index 0000000..405bc65 --- /dev/null +++ b/.svn/entries @@ -0,0 +1,133 @@ +10 + +dir +19 +svn://localhost/spr1ngsvn/TheEye/Eye +svn://localhost/spr1ngsvn/TheEye + + + +2010-06-30T03:16:43.109433Z +19 +stream +has-props + + + + + + + + + + + + + +8763ed6d-9318-4032-b958-c511fcb819a9 + + + + + + + + +() + +.git +dir + +dist +dir + +nbproject +dir + +src +dir + +manifest.mf +file + + + + +2010-06-28T07:30:17.494569Z +d6fe4af2f67849f1c01635b0ed4c443d +2010-06-28T07:29:35.843368Z +10 +spr1ng + + + + + + + + + + + + + + + + + + + + + +82 + +libs +dir + +db.db4o +file + + + +delete + +4deb3b00563d5553ef5ae1a7839c710b +2010-06-30T03:16:43.109433Z +19 +stream +has-props + +build.xml +file + + + + +2010-06-28T07:30:17.494569Z +0571c3a3ca6bb5ae9652bc8ba9aee7b9 +2010-06-28T07:29:35.843368Z +10 +spr1ng + + + + + + + + + + + + + + + + + + + + + +3630 + diff --git a/.svn/prop-base/db.db4o.svn-base b/.svn/prop-base/db.db4o.svn-base new file mode 100644 index 0000000..5e9587e --- /dev/null +++ b/.svn/prop-base/db.db4o.svn-base @@ -0,0 +1,5 @@ +K 13 +svn:mime-type +V 24 +application/octet-stream +END diff --git a/.svn/text-base/build.xml.svn-base b/.svn/text-base/build.xml.svn-base new file mode 100644 index 0000000..c782085 --- /dev/null +++ b/.svn/text-base/build.xml.svn-base @@ -0,0 +1,74 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- You may freely edit this file. See commented blocks below for --> +<!-- some examples of how to customize the build. --> +<!-- (If you delete it and reopen the project it will be recreated.) --> +<!-- By default, only the Clean and Build commands use this build script. --> +<!-- Commands such as Run, Debug, and Test only use this build script if --> +<!-- the Compile on Save feature is turned off for the project. --> +<!-- You can turn off the Compile on Save (or Deploy on Save) setting --> +<!-- in the project's Project Properties dialog box.--> +<project name="eye" default="default" basedir="."> + <description>Builds, tests, and runs the project eye.</description> + <import file="nbproject/build-impl.xml"/> + <!-- + + There exist several targets which are by default empty and which can be + used for execution of your tasks. These targets are usually executed + before and after some main targets. They are: + + -pre-init: called before initialization of project properties + -post-init: called after initialization of project properties + -pre-compile: called before javac compilation + -post-compile: called after javac compilation + -pre-compile-single: called before javac compilation of single file + -post-compile-single: called after javac compilation of single file + -pre-compile-test: called before javac compilation of JUnit tests + -post-compile-test: called after javac compilation of JUnit tests + -pre-compile-test-single: called before javac compilation of single JUnit test + -post-compile-test-single: called after javac compilation of single JUunit test + -pre-jar: called before JAR building + -post-jar: called after JAR building + -post-clean: called after cleaning build products + + (Targets beginning with '-' are not intended to be called on their own.) + + Example of inserting an obfuscator after compilation could look like this: + + <target name="-post-compile"> + <obfuscate> + <fileset dir="${build.classes.dir}"/> + </obfuscate> + </target> + + For list of available properties check the imported + nbproject/build-impl.xml file. + + + Another way to customize the build is by overriding existing main targets. + The targets of interest are: + + -init-macrodef-javac: defines macro for javac compilation + -init-macrodef-junit: defines macro for junit execution + -init-macrodef-debug: defines macro for class debugging + -init-macrodef-java: defines macro for class execution + -do-jar-with-manifest: JAR building (if you are using a manifest) + -do-jar-without-manifest: JAR building (if you are not using a manifest) + run: execution of project + -javadoc-build: Javadoc generation + test-report: JUnit report generation + + An example of overriding the target for project execution could look like this: + + <target name="run" depends="eye-impl.jar"> + <exec dir="bin" executable="launcher.exe"> + <arg file="${dist.jar}"/> + </exec> + </target> + + Notice that the overridden target depends on the jar target and not only on + the compile target as the regular run target does. Again, for a list of available + properties which you can use, check the target you are overriding in the + nbproject/build-impl.xml file. + + --> +</project> diff --git a/.svn/text-base/db.db4o.svn-base b/.svn/text-base/db.db4o.svn-base new file mode 100644 index 0000000..99c2b3e Binary files /dev/null and b/.svn/text-base/db.db4o.svn-base differ diff --git a/.svn/text-base/manifest.mf.svn-base b/.svn/text-base/manifest.mf.svn-base new file mode 100644 index 0000000..328e8e5 --- /dev/null +++ b/.svn/text-base/manifest.mf.svn-base @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +X-COMMENT: Main-Class will be added automatically by build + diff --git a/README b/README new file mode 100644 index 0000000..e69de29 diff --git a/build.xml b/build.xml new file mode 100644 index 0000000..c782085 --- /dev/null +++ b/build.xml @@ -0,0 +1,74 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- You may freely edit this file. See commented blocks below for --> +<!-- some examples of how to customize the build. --> +<!-- (If you delete it and reopen the project it will be recreated.) --> +<!-- By default, only the Clean and Build commands use this build script. --> +<!-- Commands such as Run, Debug, and Test only use this build script if --> +<!-- the Compile on Save feature is turned off for the project. --> +<!-- You can turn off the Compile on Save (or Deploy on Save) setting --> +<!-- in the project's Project Properties dialog box.--> +<project name="eye" default="default" basedir="."> + <description>Builds, tests, and runs the project eye.</description> + <import file="nbproject/build-impl.xml"/> + <!-- + + There exist several targets which are by default empty and which can be + used for execution of your tasks. These targets are usually executed + before and after some main targets. They are: + + -pre-init: called before initialization of project properties + -post-init: called after initialization of project properties + -pre-compile: called before javac compilation + -post-compile: called after javac compilation + -pre-compile-single: called before javac compilation of single file + -post-compile-single: called after javac compilation of single file + -pre-compile-test: called before javac compilation of JUnit tests + -post-compile-test: called after javac compilation of JUnit tests + -pre-compile-test-single: called before javac compilation of single JUnit test + -post-compile-test-single: called after javac compilation of single JUunit test + -pre-jar: called before JAR building + -post-jar: called after JAR building + -post-clean: called after cleaning build products + + (Targets beginning with '-' are not intended to be called on their own.) + + Example of inserting an obfuscator after compilation could look like this: + + <target name="-post-compile"> + <obfuscate> + <fileset dir="${build.classes.dir}"/> + </obfuscate> + </target> + + For list of available properties check the imported + nbproject/build-impl.xml file. + + + Another way to customize the build is by overriding existing main targets. + The targets of interest are: + + -init-macrodef-javac: defines macro for javac compilation + -init-macrodef-junit: defines macro for junit execution + -init-macrodef-debug: defines macro for class debugging + -init-macrodef-java: defines macro for class execution + -do-jar-with-manifest: JAR building (if you are using a manifest) + -do-jar-without-manifest: JAR building (if you are not using a manifest) + run: execution of project + -javadoc-build: Javadoc generation + test-report: JUnit report generation + + An example of overriding the target for project execution could look like this: + + <target name="run" depends="eye-impl.jar"> + <exec dir="bin" executable="launcher.exe"> + <arg file="${dist.jar}"/> + </exec> + </target> + + Notice that the overridden target depends on the jar target and not only on + the compile target as the regular run target does. Again, for a list of available + properties which you can use, check the target you are overriding in the + nbproject/build-impl.xml file. + + --> +</project> diff --git a/build/classes/.netbeans_automatic_build b/build/classes/.netbeans_automatic_build new file mode 100644 index 0000000..e69de29 diff --git a/build/classes/eye/DBManagerEyeImpl.class b/build/classes/eye/DBManagerEyeImpl.class new file mode 100644 index 0000000..18e7927 Binary files /dev/null and b/build/classes/eye/DBManagerEyeImpl.class differ diff --git a/build/classes/eye/Eye$1.class b/build/classes/eye/Eye$1.class new file mode 100644 index 0000000..9af2b0e Binary files /dev/null and b/build/classes/eye/Eye$1.class differ diff --git a/build/classes/eye/Eye$2.class b/build/classes/eye/Eye$2.class new file mode 100644 index 0000000..0efdf79 Binary files /dev/null and b/build/classes/eye/Eye$2.class differ diff --git a/build/classes/eye/Eye.class b/build/classes/eye/Eye.class new file mode 100644 index 0000000..17fe401 Binary files /dev/null and b/build/classes/eye/Eye.class differ diff --git a/build/classes/eye/IIException.class b/build/classes/eye/IIException.class new file mode 100644 index 0000000..3a6dbc0 Binary files /dev/null and b/build/classes/eye/IIException.class differ diff --git a/build/classes/eye/ImageFactory.class b/build/classes/eye/ImageFactory.class new file mode 100644 index 0000000..e3c66c4 Binary files /dev/null and b/build/classes/eye/ImageFactory.class differ diff --git a/build/classes/eye/models/Image.class b/build/classes/eye/models/Image.class new file mode 100644 index 0000000..b2253fc Binary files /dev/null and b/build/classes/eye/models/Image.class differ diff --git a/build/classes/eye/models/Place.class b/build/classes/eye/models/Place.class new file mode 100644 index 0000000..bccdeed Binary files /dev/null and b/build/classes/eye/models/Place.class differ diff --git a/build/classes/eye/models/Point.class b/build/classes/eye/models/Point.class new file mode 100644 index 0000000..d2135a2 Binary files /dev/null and b/build/classes/eye/models/Point.class differ diff --git a/build/classes/eye/models/RemoteSource.class b/build/classes/eye/models/RemoteSource.class new file mode 100644 index 0000000..12f3cdd Binary files /dev/null and b/build/classes/eye/models/RemoteSource.class differ diff --git a/build/classes/eye/net/InetUtils$1.class b/build/classes/eye/net/InetUtils$1.class new file mode 100644 index 0000000..0477528 Binary files /dev/null and b/build/classes/eye/net/InetUtils$1.class differ diff --git a/build/classes/eye/net/InetUtils.class b/build/classes/eye/net/InetUtils.class new file mode 100644 index 0000000..6acae90 Binary files /dev/null and b/build/classes/eye/net/InetUtils.class differ diff --git a/build/classes/log4j.xml b/build/classes/log4j.xml new file mode 100644 index 0000000..9a584ff --- /dev/null +++ b/build/classes/log4j.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> + + <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> + + <appender name="console" class="org.apache.log4j.ConsoleAppender"> + <param name="Target" value="System.out"/> + <layout class="org.apache.log4j.PatternLayout"> + <param name="ConversionPattern" value="%p %c: %m%n"/> + </layout> + </appender> + <!--Корневой logger--> + <root> + <priority value ="debug" /> + <appender-ref ref="console" /> + </root> + + </log4j:configuration> \ No newline at end of file diff --git a/dist/.svn/entries b/dist/.svn/entries new file mode 100644 index 0000000..7ea885c --- /dev/null +++ b/dist/.svn/entries @@ -0,0 +1,65 @@ +10 + +dir +19 +svn://localhost/spr1ngsvn/TheEye/Eye/dist +svn://localhost/spr1ngsvn/TheEye + + + +2010-06-30T03:16:43.109433Z +19 +stream + + + + + + + + + + + + + + +8763ed6d-9318-4032-b958-c511fcb819a9 + +lib +dir + +eye.jar +file +28 + + + +2010-07-01T05:27:54.362573Z +85d087ca1a76141ad806519995e4127a +2010-07-01T05:35:24.601857Z +28 +spr1ng +has-props + + + + + + + + + + + + + + + + + + + + +34123 + diff --git a/dist/.svn/prop-base/eye.jar.svn-base b/dist/.svn/prop-base/eye.jar.svn-base new file mode 100644 index 0000000..5e9587e --- /dev/null +++ b/dist/.svn/prop-base/eye.jar.svn-base @@ -0,0 +1,5 @@ +K 13 +svn:mime-type +V 24 +application/octet-stream +END diff --git a/dist/.svn/text-base/eye.jar.svn-base b/dist/.svn/text-base/eye.jar.svn-base new file mode 100644 index 0000000..c813263 Binary files /dev/null and b/dist/.svn/text-base/eye.jar.svn-base differ diff --git a/dist/README.TXT b/dist/README.TXT new file mode 100644 index 0000000..2481765 --- /dev/null +++ b/dist/README.TXT @@ -0,0 +1,33 @@ +======================== +BUILD OUTPUT DESCRIPTION +======================== + +When you build an Java application project that has a main class, the IDE +automatically copies all of the JAR +files on the projects classpath to your projects dist/lib folder. The IDE +also adds each of the JAR files to the Class-Path element in the application +JAR files manifest file (MANIFEST.MF). + +To run the project from the command line, go to the dist folder and +type the following: + +java -jar "eye.jar" + +To distribute this project, zip up the dist folder (including the lib folder) +and distribute the ZIP file. + +Notes: + +* If two JAR files on the project classpath have the same name, only the first +JAR file is copied to the lib folder. +* Only JAR files are copied to the lib folder. +If the classpath contains other types of files or folders, none of the +classpath elements are copied to the lib folder. In such a case, +you need to copy the classpath elements to the lib folder manually after the build. +* If a library on the projects classpath also has a Class-Path element +specified in the manifest,the content of the Class-Path element has to be on +the projects runtime path. +* To set a main class in a standard Java project, right-click the project node +in the Projects window and choose Properties. Then click Run and enter the +class name in the Main Class field. Alternatively, you can manually type the +class name in the manifest Main-Class element. diff --git a/dist/eye.jar b/dist/eye.jar new file mode 100644 index 0000000..c813263 Binary files /dev/null and b/dist/eye.jar differ diff --git a/dist/lib/.svn/entries b/dist/lib/.svn/entries new file mode 100644 index 0000000..5a9c75f --- /dev/null +++ b/dist/lib/.svn/entries @@ -0,0 +1,118 @@ +10 + +dir +19 +svn://localhost/spr1ngsvn/TheEye/Eye/dist/lib +svn://localhost/spr1ngsvn/TheEye + + + +2010-06-30T03:16:43.109433Z +19 +stream + + + + + + + + + + + + + + +8763ed6d-9318-4032-b958-c511fcb819a9 + + + + + + + + +() + +DB4o-Server.jar +file + + + +delete + +9e6b965bbbf187fde81863631a7bc86c +2010-06-30T03:16:43.109433Z +19 +stream +has-props + +db4o-7.12.145.14409-all-java5.jar +file + + + + +2010-06-28T07:30:12.631071Z +bd8d235631a171e277fcee08bdc9bb9f +2010-06-28T07:29:35.843368Z +10 +spr1ng +has-props + + + + + + + + + + + + + + + + + + + + +2445257 + +log4j-1.2.15.jar +file + + + + +2010-06-28T07:30:12.631071Z +4d4609998fbc124ce6f0d1d48fca2614 +2010-06-28T07:29:35.843368Z +10 +spr1ng +has-props + + + + + + + + + + + + + + + + + + + + +391834 + diff --git a/dist/lib/.svn/prop-base/DB4o-Server.jar.svn-base b/dist/lib/.svn/prop-base/DB4o-Server.jar.svn-base new file mode 100644 index 0000000..5e9587e --- /dev/null +++ b/dist/lib/.svn/prop-base/DB4o-Server.jar.svn-base @@ -0,0 +1,5 @@ +K 13 +svn:mime-type +V 24 +application/octet-stream +END diff --git a/dist/lib/.svn/prop-base/db4o-7.12.145.14409-all-java5.jar.svn-base b/dist/lib/.svn/prop-base/db4o-7.12.145.14409-all-java5.jar.svn-base new file mode 100644 index 0000000..5e9587e --- /dev/null +++ b/dist/lib/.svn/prop-base/db4o-7.12.145.14409-all-java5.jar.svn-base @@ -0,0 +1,5 @@ +K 13 +svn:mime-type +V 24 +application/octet-stream +END diff --git a/dist/lib/.svn/prop-base/log4j-1.2.15.jar.svn-base b/dist/lib/.svn/prop-base/log4j-1.2.15.jar.svn-base new file mode 100644 index 0000000..5e9587e --- /dev/null +++ b/dist/lib/.svn/prop-base/log4j-1.2.15.jar.svn-base @@ -0,0 +1,5 @@ +K 13 +svn:mime-type +V 24 +application/octet-stream +END diff --git a/dist/lib/.svn/text-base/DB4o-Server.jar.svn-base b/dist/lib/.svn/text-base/DB4o-Server.jar.svn-base new file mode 100644 index 0000000..fd0b5bd Binary files /dev/null and b/dist/lib/.svn/text-base/DB4o-Server.jar.svn-base differ diff --git a/dist/lib/.svn/text-base/db4o-7.12.145.14409-all-java5.jar.svn-base b/dist/lib/.svn/text-base/db4o-7.12.145.14409-all-java5.jar.svn-base new file mode 100644 index 0000000..8316271 Binary files /dev/null and b/dist/lib/.svn/text-base/db4o-7.12.145.14409-all-java5.jar.svn-base differ diff --git a/dist/lib/.svn/text-base/log4j-1.2.15.jar.svn-base b/dist/lib/.svn/text-base/log4j-1.2.15.jar.svn-base new file mode 100644 index 0000000..c930a6a Binary files /dev/null and b/dist/lib/.svn/text-base/log4j-1.2.15.jar.svn-base differ diff --git a/dist/lib/DB4o-Server.jar b/dist/lib/DB4o-Server.jar new file mode 100644 index 0000000..7a2a7cc Binary files /dev/null and b/dist/lib/DB4o-Server.jar differ diff --git a/dist/lib/db4o-7.12.145.14409-all-java5.jar b/dist/lib/db4o-7.12.145.14409-all-java5.jar new file mode 100644 index 0000000..8316271 Binary files /dev/null and b/dist/lib/db4o-7.12.145.14409-all-java5.jar differ diff --git a/dist/lib/log4j-1.2.15.jar b/dist/lib/log4j-1.2.15.jar new file mode 100644 index 0000000..c930a6a Binary files /dev/null and b/dist/lib/log4j-1.2.15.jar differ diff --git a/libs/.svn/entries b/libs/.svn/entries new file mode 100644 index 0000000..ba5619f --- /dev/null +++ b/libs/.svn/entries @@ -0,0 +1,96 @@ +10 + +dir +19 +svn://localhost/spr1ngsvn/TheEye/Eye/libs +svn://localhost/spr1ngsvn/TheEye + + + +2010-06-29T03:24:59.818237Z +16 +spr1ng + + + + + + + + + + + + + + +8763ed6d-9318-4032-b958-c511fcb819a9 + +db4o-7.12.145.14409-all-java5.jar +file + + + + +2010-06-28T07:30:16.134571Z +bd8d235631a171e277fcee08bdc9bb9f +2010-06-28T07:29:35.843368Z +10 +spr1ng +has-props + + + + + + + + + + + + + + + + + + + + +2445257 + +log4j-1.2.15.jar +file + + + + +2010-06-28T07:30:16.142570Z +4d4609998fbc124ce6f0d1d48fca2614 +2010-06-28T07:29:35.843368Z +10 +spr1ng +has-props + + + + + + + + + + + + + + + + + + + + +391834 + diff --git a/libs/.svn/prop-base/db4o-7.12.145.14409-all-java5.jar.svn-base b/libs/.svn/prop-base/db4o-7.12.145.14409-all-java5.jar.svn-base new file mode 100644 index 0000000..5e9587e --- /dev/null +++ b/libs/.svn/prop-base/db4o-7.12.145.14409-all-java5.jar.svn-base @@ -0,0 +1,5 @@ +K 13 +svn:mime-type +V 24 +application/octet-stream +END diff --git a/libs/.svn/prop-base/log4j-1.2.15.jar.svn-base b/libs/.svn/prop-base/log4j-1.2.15.jar.svn-base new file mode 100644 index 0000000..5e9587e --- /dev/null +++ b/libs/.svn/prop-base/log4j-1.2.15.jar.svn-base @@ -0,0 +1,5 @@ +K 13 +svn:mime-type +V 24 +application/octet-stream +END diff --git a/libs/.svn/text-base/db4o-7.12.145.14409-all-java5.jar.svn-base b/libs/.svn/text-base/db4o-7.12.145.14409-all-java5.jar.svn-base new file mode 100644 index 0000000..8316271 Binary files /dev/null and b/libs/.svn/text-base/db4o-7.12.145.14409-all-java5.jar.svn-base differ diff --git a/libs/.svn/text-base/log4j-1.2.15.jar.svn-base b/libs/.svn/text-base/log4j-1.2.15.jar.svn-base new file mode 100644 index 0000000..c930a6a Binary files /dev/null and b/libs/.svn/text-base/log4j-1.2.15.jar.svn-base differ diff --git a/libs/db4o-7.12.145.14409-all-java5.jar b/libs/db4o-7.12.145.14409-all-java5.jar new file mode 100644 index 0000000..8316271 Binary files /dev/null and b/libs/db4o-7.12.145.14409-all-java5.jar differ diff --git a/libs/log4j-1.2.15.jar b/libs/log4j-1.2.15.jar new file mode 100644 index 0000000..c930a6a Binary files /dev/null and b/libs/log4j-1.2.15.jar differ diff --git a/manifest.mf b/manifest.mf new file mode 100644 index 0000000..328e8e5 --- /dev/null +++ b/manifest.mf @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +X-COMMENT: Main-Class will be added automatically by build + diff --git a/nbproject/.svn/entries b/nbproject/.svn/entries new file mode 100644 index 0000000..c9edbcf --- /dev/null +++ b/nbproject/.svn/entries @@ -0,0 +1,167 @@ +10 + +dir +19 +svn://localhost/spr1ngsvn/TheEye/Eye/nbproject +svn://localhost/spr1ngsvn/TheEye + + + +2010-06-28T07:29:35.843368Z +10 +spr1ng + + + + + + + + + + + + + + +8763ed6d-9318-4032-b958-c511fcb819a9 + +project.properties +file + + + + +2010-06-28T07:30:12.643069Z +6f695dff7cd7ee233355fec38134470b +2010-06-28T07:29:35.843368Z +10 +spr1ng + + + + + + + + + + + + + + + + + + + + + +2428 + +project.xml +file + + + + +2010-06-28T07:30:12.643069Z +ac54815196fe952c7a6edcec31fd9a53 +2010-06-28T07:29:35.843368Z +10 +spr1ng + + + + + + + + + + + + + + + + + + + + + +922 + +genfiles.properties +file + + + + +2010-06-28T07:30:12.643069Z +37346fef93e45345f049998768e31a4e +2010-06-28T07:29:35.843368Z +10 +spr1ng + + + + + + + + + + + + + + + + + + + + + +467 + +private +dir + +build-impl.xml +file + + + + +2010-06-28T07:30:12.643069Z +4a5a893fc1143659600d8d906e145d72 +2010-06-28T07:29:35.843368Z +10 +spr1ng + + + + + + + + + + + + + + + + + + + + + +43323 + diff --git a/nbproject/.svn/text-base/build-impl.xml.svn-base b/nbproject/.svn/text-base/build-impl.xml.svn-base new file mode 100644 index 0000000..e5f30a8 --- /dev/null +++ b/nbproject/.svn/text-base/build-impl.xml.svn-base @@ -0,0 +1,819 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- +*** GENERATED FROM project.xml - DO NOT EDIT *** +*** EDIT ../build.xml INSTEAD *** + +For the purpose of easier reading the script +is divided into following sections: + + - initialization + - compilation + - jar + - execution + - debugging + - javadoc + - junit compilation + - junit execution + - junit debugging + - applet + - cleanup + + --> +<project xmlns:j2seproject1="http://www.netbeans.org/ns/j2se-project/1" xmlns:j2seproject3="http://www.netbeans.org/ns/j2se-project/3" xmlns:jaxrpc="http://www.netbeans.org/ns/j2se-project/jax-rpc" basedir=".." default="default" name="eye-impl"> + <fail message="Please build using Ant 1.7.1 or higher."> + <condition> + <not> + <antversion atleast="1.7.1"/> + </not> + </condition> + </fail> + <target depends="test,jar,javadoc" description="Build and test whole project." name="default"/> + <!-- + ====================== + INITIALIZATION SECTION + ====================== + --> + <target name="-pre-init"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="-pre-init" name="-init-private"> + <property file="nbproject/private/config.properties"/> + <property file="nbproject/private/configs/${config}.properties"/> + <property file="nbproject/private/private.properties"/> + </target> + <target depends="-pre-init,-init-private" name="-init-user"> + <property file="${user.properties.file}"/> + <!-- The two properties below are usually overridden --> + <!-- by the active platform. Just a fallback. --> + <property name="default.javac.source" value="1.4"/> + <property name="default.javac.target" value="1.4"/> + </target> + <target depends="-pre-init,-init-private,-init-user" name="-init-project"> + <property file="nbproject/configs/${config}.properties"/> + <property file="nbproject/project.properties"/> + </target> + <target depends="-pre-init,-init-private,-init-user,-init-project,-init-macrodef-property" name="-do-init"> + <available file="${manifest.file}" property="manifest.available"/> + <condition property="main.class.available"> + <and> + <isset property="main.class"/> + <not> + <equals arg1="${main.class}" arg2="" trim="true"/> + </not> + </and> + </condition> + <condition property="manifest.available+main.class"> + <and> + <isset property="manifest.available"/> + <isset property="main.class.available"/> + </and> + </condition> + <condition property="do.mkdist"> + <and> + <isset property="libs.CopyLibs.classpath"/> + <not> + <istrue value="${mkdist.disabled}"/> + </not> + </and> + </condition> + <condition property="manifest.available+main.class+mkdist.available"> + <and> + <istrue value="${manifest.available+main.class}"/> + <isset property="do.mkdist"/> + </and> + </condition> + <condition property="manifest.available+mkdist.available"> + <and> + <istrue value="${manifest.available}"/> + <isset property="do.mkdist"/> + </and> + </condition> + <condition property="manifest.available-mkdist.available"> + <or> + <istrue value="${manifest.available}"/> + <isset property="do.mkdist"/> + </or> + </condition> + <condition property="manifest.available+main.class-mkdist.available"> + <or> + <istrue value="${manifest.available+main.class}"/> + <isset property="do.mkdist"/> + </or> + </condition> + <condition property="have.tests"> + <or> + <available file="${test.src.dir}"/> + </or> + </condition> + <condition property="have.sources"> + <or> + <available file="${src.dir}"/> + </or> + </condition> + <condition property="netbeans.home+have.tests"> + <and> + <isset property="netbeans.home"/> + <isset property="have.tests"/> + </and> + </condition> + <condition property="no.javadoc.preview"> + <and> + <isset property="javadoc.preview"/> + <isfalse value="${javadoc.preview}"/> + </and> + </condition> + <property name="run.jvmargs" value=""/> + <property name="javac.compilerargs" value=""/> + <property name="work.dir" value="${basedir}"/> + <condition property="no.deps"> + <and> + <istrue value="${no.dependencies}"/> + </and> + </condition> + <property name="javac.debug" value="true"/> + <property name="javadoc.preview" value="true"/> + <property name="application.args" value=""/> + <property name="source.encoding" value="${file.encoding}"/> + <property name="runtime.encoding" value="${source.encoding}"/> + <condition property="javadoc.encoding.used" value="${javadoc.encoding}"> + <and> + <isset property="javadoc.encoding"/> + <not> + <equals arg1="${javadoc.encoding}" arg2=""/> + </not> + </and> + </condition> + <property name="javadoc.encoding.used" value="${source.encoding}"/> + <property name="includes" value="**"/> + <property name="excludes" value=""/> + <property name="do.depend" value="false"/> + <condition property="do.depend.true"> + <istrue value="${do.depend}"/> + </condition> + <path id="endorsed.classpath.path" path="${endorsed.classpath}"/> + <condition else="" property="endorsed.classpath.cmd.line.arg" value="-Xbootclasspath/p:'${toString:endorsed.classpath.path}'"> + <length length="0" string="${endorsed.classpath}" when="greater"/> + </condition> + <property name="javac.fork" value="false"/> + </target> + <target name="-post-init"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="-pre-init,-init-private,-init-user,-init-project,-do-init" name="-init-check"> + <fail unless="src.dir">Must set src.dir</fail> + <fail unless="test.src.dir">Must set test.src.dir</fail> + <fail unless="build.dir">Must set build.dir</fail> + <fail unless="dist.dir">Must set dist.dir</fail> + <fail unless="build.classes.dir">Must set build.classes.dir</fail> + <fail unless="dist.javadoc.dir">Must set dist.javadoc.dir</fail> + <fail unless="build.test.classes.dir">Must set build.test.classes.dir</fail> + <fail unless="build.test.results.dir">Must set build.test.results.dir</fail> + <fail unless="build.classes.excludes">Must set build.classes.excludes</fail> + <fail unless="dist.jar">Must set dist.jar</fail> + </target> + <target name="-init-macrodef-property"> + <macrodef name="property" uri="http://www.netbeans.org/ns/j2se-project/1"> + <attribute name="name"/> + <attribute name="value"/> + <sequential> + <property name="@{name}" value="${@{value}}"/> + </sequential> + </macrodef> + </target> + <target name="-init-macrodef-javac"> + <macrodef name="javac" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${src.dir}" name="srcdir"/> + <attribute default="${build.classes.dir}" name="destdir"/> + <attribute default="${javac.classpath}" name="classpath"/> + <attribute default="${includes}" name="includes"/> + <attribute default="${excludes}" name="excludes"/> + <attribute default="${javac.debug}" name="debug"/> + <attribute default="${empty.dir}" name="sourcepath"/> + <attribute default="${empty.dir}" name="gensrcdir"/> + <element name="customize" optional="true"/> + <sequential> + <property location="${build.dir}/empty" name="empty.dir"/> + <mkdir dir="${empty.dir}"/> + <javac debug="@{debug}" deprecation="${javac.deprecation}" destdir="@{destdir}" encoding="${source.encoding}" excludes="@{excludes}" fork="${javac.fork}" includeantruntime="false" includes="@{includes}" source="${javac.source}" sourcepath="@{sourcepath}" srcdir="@{srcdir}" target="${javac.target}" tempdir="${java.io.tmpdir}"> + <src> + <dirset dir="@{gensrcdir}" erroronmissingdir="false"> + <include name="*"/> + </dirset> + </src> + <classpath> + <path path="@{classpath}"/> + </classpath> + <compilerarg line="${endorsed.classpath.cmd.line.arg}"/> + <compilerarg line="${javac.compilerargs}"/> + <customize/> + </javac> + </sequential> + </macrodef> + <macrodef name="depend" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${src.dir}" name="srcdir"/> + <attribute default="${build.classes.dir}" name="destdir"/> + <attribute default="${javac.classpath}" name="classpath"/> + <sequential> + <depend cache="${build.dir}/depcache" destdir="@{destdir}" excludes="${excludes}" includes="${includes}" srcdir="@{srcdir}"> + <classpath> + <path path="@{classpath}"/> + </classpath> + </depend> + </sequential> + </macrodef> + <macrodef name="force-recompile" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${build.classes.dir}" name="destdir"/> + <sequential> + <fail unless="javac.includes">Must set javac.includes</fail> + <pathconvert pathsep="," property="javac.includes.binary"> + <path> + <filelist dir="@{destdir}" files="${javac.includes}"/> + </path> + <globmapper from="*.java" to="*.class"/> + </pathconvert> + <delete> + <files includes="${javac.includes.binary}"/> + </delete> + </sequential> + </macrodef> + </target> + <target name="-init-macrodef-junit"> + <macrodef name="junit" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${includes}" name="includes"/> + <attribute default="${excludes}" name="excludes"/> + <attribute default="**" name="testincludes"/> + <sequential> + <junit dir="${work.dir}" errorproperty="tests.failed" failureproperty="tests.failed" fork="true" showoutput="true" tempdir="${build.dir}"> + <batchtest todir="${build.test.results.dir}"> + <fileset dir="${test.src.dir}" excludes="@{excludes},${excludes}" includes="@{includes}"> + <filename name="@{testincludes}"/> + </fileset> + </batchtest> + <classpath> + <path path="${run.test.classpath}"/> + </classpath> + <syspropertyset> + <propertyref prefix="test-sys-prop."/> + <mapper from="test-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + <formatter type="brief" usefile="false"/> + <formatter type="xml"/> + <jvmarg line="${endorsed.classpath.cmd.line.arg}"/> + <jvmarg line="${run.jvmargs}"/> + </junit> + </sequential> + </macrodef> + </target> + <target depends="-init-debug-args" name="-init-macrodef-nbjpda"> + <macrodef name="nbjpdastart" uri="http://www.netbeans.org/ns/j2se-project/1"> + <attribute default="${main.class}" name="name"/> + <attribute default="${debug.classpath}" name="classpath"/> + <attribute default="" name="stopclassname"/> + <sequential> + <nbjpdastart addressproperty="jpda.address" name="@{name}" stopclassname="@{stopclassname}" transport="${debug-transport}"> + <classpath> + <path path="@{classpath}"/> + </classpath> + </nbjpdastart> + </sequential> + </macrodef> + <macrodef name="nbjpdareload" uri="http://www.netbeans.org/ns/j2se-project/1"> + <attribute default="${build.classes.dir}" name="dir"/> + <sequential> + <nbjpdareload> + <fileset dir="@{dir}" includes="${fix.classes}"> + <include name="${fix.includes}*.class"/> + </fileset> + </nbjpdareload> + </sequential> + </macrodef> + </target> + <target name="-init-debug-args"> + <property name="version-output" value="java version &quot;${ant.java.version}"/> + <condition property="have-jdk-older-than-1.4"> + <or> + <contains string="${version-output}" substring="java version &quot;1.0"/> + <contains string="${version-output}" substring="java version &quot;1.1"/> + <contains string="${version-output}" substring="java version &quot;1.2"/> + <contains string="${version-output}" substring="java version &quot;1.3"/> + </or> + </condition> + <condition else="-Xdebug" property="debug-args-line" value="-Xdebug -Xnoagent -Djava.compiler=none"> + <istrue value="${have-jdk-older-than-1.4}"/> + </condition> + <condition else="dt_socket" property="debug-transport-by-os" value="dt_shmem"> + <os family="windows"/> + </condition> + <condition else="${debug-transport-by-os}" property="debug-transport" value="${debug.transport}"> + <isset property="debug.transport"/> + </condition> + </target> + <target depends="-init-debug-args" name="-init-macrodef-debug"> + <macrodef name="debug" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${main.class}" name="classname"/> + <attribute default="${debug.classpath}" name="classpath"/> + <element name="customize" optional="true"/> + <sequential> + <java classname="@{classname}" dir="${work.dir}" fork="true"> + <jvmarg line="${endorsed.classpath.cmd.line.arg}"/> + <jvmarg line="${debug-args-line}"/> + <jvmarg value="-Xrunjdwp:transport=${debug-transport},address=${jpda.address}"/> + <jvmarg value="-Dfile.encoding=${runtime.encoding}"/> + <redirector errorencoding="${runtime.encoding}" inputencoding="${runtime.encoding}" outputencoding="${runtime.encoding}"/> + <jvmarg line="${run.jvmargs}"/> + <classpath> + <path path="@{classpath}"/> + </classpath> + <syspropertyset> + <propertyref prefix="run-sys-prop."/> + <mapper from="run-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + <customize/> + </java> + </sequential> + </macrodef> + </target> + <target name="-init-macrodef-java"> + <macrodef name="java" uri="http://www.netbeans.org/ns/j2se-project/1"> + <attribute default="${main.class}" name="classname"/> + <attribute default="${run.classpath}" name="classpath"/> + <element name="customize" optional="true"/> + <sequential> + <java classname="@{classname}" dir="${work.dir}" fork="true"> + <jvmarg line="${endorsed.classpath.cmd.line.arg}"/> + <jvmarg value="-Dfile.encoding=${runtime.encoding}"/> + <redirector errorencoding="${runtime.encoding}" inputencoding="${runtime.encoding}" outputencoding="${runtime.encoding}"/> + <jvmarg line="${run.jvmargs}"/> + <classpath> + <path path="@{classpath}"/> + </classpath> + <syspropertyset> + <propertyref prefix="run-sys-prop."/> + <mapper from="run-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + <customize/> + </java> + </sequential> + </macrodef> + </target> + <target name="-init-presetdef-jar"> + <presetdef name="jar" uri="http://www.netbeans.org/ns/j2se-project/1"> + <jar compress="${jar.compress}" jarfile="${dist.jar}"> + <j2seproject1:fileset dir="${build.classes.dir}"/> + </jar> + </presetdef> + </target> + <target depends="-pre-init,-init-private,-init-user,-init-project,-do-init,-post-init,-init-check,-init-macrodef-property,-init-macrodef-javac,-init-macrodef-junit,-init-macrodef-nbjpda,-init-macrodef-debug,-init-macrodef-java,-init-presetdef-jar" name="init"/> + <!-- + =================== + COMPILATION SECTION + =================== + --> + <target name="-deps-jar-init" unless="built-jar.properties"> + <property location="${build.dir}/built-jar.properties" name="built-jar.properties"/> + <delete file="${built-jar.properties}" quiet="true"/> + </target> + <target if="already.built.jar.${basedir}" name="-warn-already-built-jar"> + <echo level="warn" message="Cycle detected: eye was already built"/> + </target> + <target depends="init,-deps-jar-init" name="deps-jar" unless="no.deps"> + <mkdir dir="${build.dir}"/> + <touch file="${built-jar.properties}" verbose="false"/> + <property file="${built-jar.properties}" prefix="already.built.jar."/> + <antcall target="-warn-already-built-jar"/> + <propertyfile file="${built-jar.properties}"> + <entry key="${basedir}" value=""/> + </propertyfile> + <antcall target="-maybe-call-dep"> + <param name="call.built.properties" value="${built-jar.properties}"/> + <param location="${project.DB4o-Server}" name="call.subproject"/> + <param location="${project.DB4o-Server}/build.xml" name="call.script"/> + <param name="call.target" value="jar"/> + <param name="transfer.built-jar.properties" value="${built-jar.properties}"/> + </antcall> + </target> + <target depends="init,-check-automatic-build,-clean-after-automatic-build" name="-verify-automatic-build"/> + <target depends="init" name="-check-automatic-build"> + <available file="${build.classes.dir}/.netbeans_automatic_build" property="netbeans.automatic.build"/> + </target> + <target depends="init" if="netbeans.automatic.build" name="-clean-after-automatic-build"> + <antcall target="clean"/> + </target> + <target depends="init,deps-jar" name="-pre-pre-compile"> + <mkdir dir="${build.classes.dir}"/> + </target> + <target name="-pre-compile"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target if="do.depend.true" name="-compile-depend"> + <pathconvert property="build.generated.subdirs"> + <dirset dir="${build.generated.sources.dir}" erroronmissingdir="false"> + <include name="*"/> + </dirset> + </pathconvert> + <j2seproject3:depend srcdir="${src.dir}:${build.generated.subdirs}"/> + </target> + <target depends="init,deps-jar,-pre-pre-compile,-pre-compile,-compile-depend" if="have.sources" name="-do-compile"> + <j2seproject3:javac gensrcdir="${build.generated.sources.dir}"/> + <copy todir="${build.classes.dir}"> + <fileset dir="${src.dir}" excludes="${build.classes.excludes},${excludes}" includes="${includes}"/> + </copy> + </target> + <target name="-post-compile"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,deps-jar,-verify-automatic-build,-pre-pre-compile,-pre-compile,-do-compile,-post-compile" description="Compile project." name="compile"/> + <target name="-pre-compile-single"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,deps-jar,-pre-pre-compile" name="-do-compile-single"> + <fail unless="javac.includes">Must select some files in the IDE or set javac.includes</fail> + <j2seproject3:force-recompile/> + <j2seproject3:javac excludes="" gensrcdir="${build.generated.sources.dir}" includes="${javac.includes}" sourcepath="${src.dir}"/> + </target> + <target name="-post-compile-single"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,deps-jar,-verify-automatic-build,-pre-pre-compile,-pre-compile-single,-do-compile-single,-post-compile-single" name="compile-single"/> + <!-- + ==================== + JAR BUILDING SECTION + ==================== + --> + <target depends="init" name="-pre-pre-jar"> + <dirname file="${dist.jar}" property="dist.jar.dir"/> + <mkdir dir="${dist.jar.dir}"/> + </target> + <target name="-pre-jar"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,compile,-pre-pre-jar,-pre-jar" name="-do-jar-without-manifest" unless="manifest.available-mkdist.available"> + <j2seproject1:jar/> + </target> + <target depends="init,compile,-pre-pre-jar,-pre-jar" if="manifest.available" name="-do-jar-with-manifest" unless="manifest.available+main.class-mkdist.available"> + <j2seproject1:jar manifest="${manifest.file}"/> + </target> + <target depends="init,compile,-pre-pre-jar,-pre-jar" if="manifest.available+main.class" name="-do-jar-with-mainclass" unless="manifest.available+main.class+mkdist.available"> + <j2seproject1:jar manifest="${manifest.file}"> + <j2seproject1:manifest> + <j2seproject1:attribute name="Main-Class" value="${main.class}"/> + </j2seproject1:manifest> + </j2seproject1:jar> + <echo>To run this application from the command line without Ant, try:</echo> + <property location="${build.classes.dir}" name="build.classes.dir.resolved"/> + <property location="${dist.jar}" name="dist.jar.resolved"/> + <pathconvert property="run.classpath.with.dist.jar"> + <path path="${run.classpath}"/> + <map from="${build.classes.dir.resolved}" to="${dist.jar.resolved}"/> + </pathconvert> + <echo>java -cp "${run.classpath.with.dist.jar}" ${main.class}</echo> + </target> + <target depends="init,compile,-pre-pre-jar,-pre-jar" if="manifest.available+main.class+mkdist.available" name="-do-jar-with-libraries"> + <property location="${build.classes.dir}" name="build.classes.dir.resolved"/> + <pathconvert property="run.classpath.without.build.classes.dir"> + <path path="${run.classpath}"/> + <map from="${build.classes.dir.resolved}" to=""/> + </pathconvert> + <pathconvert pathsep=" " property="jar.classpath"> + <path path="${run.classpath.without.build.classes.dir}"/> + <chainedmapper> + <flattenmapper/> + <globmapper from="*" to="lib/*"/> + </chainedmapper> + </pathconvert> + <taskdef classname="org.netbeans.modules.java.j2seproject.copylibstask.CopyLibs" classpath="${libs.CopyLibs.classpath}" name="copylibs"/> + <copylibs compress="${jar.compress}" jarfile="${dist.jar}" manifest="${manifest.file}" runtimeclasspath="${run.classpath.without.build.classes.dir}"> + <fileset dir="${build.classes.dir}"/> + <manifest> + <attribute name="Main-Class" value="${main.class}"/> + <attribute name="Class-Path" value="${jar.classpath}"/> + </manifest> + </copylibs> + <echo>To run this application from the command line without Ant, try:</echo> + <property location="${dist.jar}" name="dist.jar.resolved"/> + <echo>java -jar "${dist.jar.resolved}"</echo> + </target> + <target depends="init,compile,-pre-pre-jar,-pre-jar" if="manifest.available+mkdist.available" name="-do-jar-with-libraries-without-mainclass" unless="main.class.available"> + <property location="${build.classes.dir}" name="build.classes.dir.resolved"/> + <pathconvert property="run.classpath.without.build.classes.dir"> + <path path="${run.classpath}"/> + <map from="${build.classes.dir.resolved}" to=""/> + </pathconvert> + <pathconvert pathsep=" " property="jar.classpath"> + <path path="${run.classpath.without.build.classes.dir}"/> + <chainedmapper> + <flattenmapper/> + <globmapper from="*" to="lib/*"/> + </chainedmapper> + </pathconvert> + <taskdef classname="org.netbeans.modules.java.j2seproject.copylibstask.CopyLibs" classpath="${libs.CopyLibs.classpath}" name="copylibs"/> + <copylibs compress="${jar.compress}" jarfile="${dist.jar}" manifest="${manifest.file}" runtimeclasspath="${run.classpath.without.build.classes.dir}"> + <fileset dir="${build.classes.dir}"/> + <manifest> + <attribute name="Class-Path" value="${jar.classpath}"/> + </manifest> + </copylibs> + </target> + <target depends="init,compile,-pre-pre-jar,-pre-jar" if="do.mkdist" name="-do-jar-with-libraries-without-manifest" unless="manifest.available"> + <property location="${build.classes.dir}" name="build.classes.dir.resolved"/> + <pathconvert property="run.classpath.without.build.classes.dir"> + <path path="${run.classpath}"/> + <map from="${build.classes.dir.resolved}" to=""/> + </pathconvert> + <pathconvert pathsep=" " property="jar.classpath"> + <path path="${run.classpath.without.build.classes.dir}"/> + <chainedmapper> + <flattenmapper/> + <globmapper from="*" to="lib/*"/> + </chainedmapper> + </pathconvert> + <taskdef classname="org.netbeans.modules.java.j2seproject.copylibstask.CopyLibs" classpath="${libs.CopyLibs.classpath}" name="copylibs"/> + <copylibs compress="${jar.compress}" jarfile="${dist.jar}" runtimeclasspath="${run.classpath.without.build.classes.dir}"> + <fileset dir="${build.classes.dir}"/> + <manifest> + <attribute name="Class-Path" value="${jar.classpath}"/> + </manifest> + </copylibs> + </target> + <target name="-post-jar"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,compile,-pre-jar,-do-jar-with-manifest,-do-jar-without-manifest,-do-jar-with-mainclass,-do-jar-with-libraries,-do-jar-with-libraries-without-mainclass,-do-jar-with-libraries-without-manifest,-post-jar" description="Build JAR." name="jar"/> + <!-- + ================= + EXECUTION SECTION + ================= + --> + <target depends="init,compile" description="Run a main class." name="run"> + <j2seproject1:java> + <customize> + <arg line="${application.args}"/> + </customize> + </j2seproject1:java> + </target> + <target name="-do-not-recompile"> + <property name="javac.includes.binary" value=""/> + </target> + <target depends="init,compile-single" name="run-single"> + <fail unless="run.class">Must select one file in the IDE or set run.class</fail> + <j2seproject1:java classname="${run.class}"/> + </target> + <target depends="init,compile-test-single" name="run-test-with-main"> + <fail unless="run.class">Must select one file in the IDE or set run.class</fail> + <j2seproject1:java classname="${run.class}" classpath="${run.test.classpath}"/> + </target> + <!-- + ================= + DEBUGGING SECTION + ================= + --> + <target depends="init" if="netbeans.home" name="-debug-start-debugger"> + <j2seproject1:nbjpdastart name="${debug.class}"/> + </target> + <target depends="init" if="netbeans.home" name="-debug-start-debugger-main-test"> + <j2seproject1:nbjpdastart classpath="${debug.test.classpath}" name="${debug.class}"/> + </target> + <target depends="init,compile" name="-debug-start-debuggee"> + <j2seproject3:debug> + <customize> + <arg line="${application.args}"/> + </customize> + </j2seproject3:debug> + </target> + <target depends="init,compile,-debug-start-debugger,-debug-start-debuggee" description="Debug project in IDE." if="netbeans.home" name="debug"/> + <target depends="init" if="netbeans.home" name="-debug-start-debugger-stepinto"> + <j2seproject1:nbjpdastart stopclassname="${main.class}"/> + </target> + <target depends="init,compile,-debug-start-debugger-stepinto,-debug-start-debuggee" if="netbeans.home" name="debug-stepinto"/> + <target depends="init,compile-single" if="netbeans.home" name="-debug-start-debuggee-single"> + <fail unless="debug.class">Must select one file in the IDE or set debug.class</fail> + <j2seproject3:debug classname="${debug.class}"/> + </target> + <target depends="init,compile-single,-debug-start-debugger,-debug-start-debuggee-single" if="netbeans.home" name="debug-single"/> + <target depends="init,compile-test-single" if="netbeans.home" name="-debug-start-debuggee-main-test"> + <fail unless="debug.class">Must select one file in the IDE or set debug.class</fail> + <j2seproject3:debug classname="${debug.class}" classpath="${debug.test.classpath}"/> + </target> + <target depends="init,compile-test-single,-debug-start-debugger-main-test,-debug-start-debuggee-main-test" if="netbeans.home" name="debug-test-with-main"/> + <target depends="init" name="-pre-debug-fix"> + <fail unless="fix.includes">Must set fix.includes</fail> + <property name="javac.includes" value="${fix.includes}.java"/> + </target> + <target depends="init,-pre-debug-fix,compile-single" if="netbeans.home" name="-do-debug-fix"> + <j2seproject1:nbjpdareload/> + </target> + <target depends="init,-pre-debug-fix,-do-debug-fix" if="netbeans.home" name="debug-fix"/> + <!-- + =============== + JAVADOC SECTION + =============== + --> + <target depends="init" name="-javadoc-build"> + <mkdir dir="${dist.javadoc.dir}"/> + <javadoc additionalparam="${javadoc.additionalparam}" author="${javadoc.author}" charset="UTF-8" destdir="${dist.javadoc.dir}" docencoding="UTF-8" encoding="${javadoc.encoding.used}" failonerror="true" noindex="${javadoc.noindex}" nonavbar="${javadoc.nonavbar}" notree="${javadoc.notree}" private="${javadoc.private}" source="${javac.source}" splitindex="${javadoc.splitindex}" use="${javadoc.use}" useexternalfile="true" version="${javadoc.version}" windowtitle="${javadoc.windowtitle}"> + <classpath> + <path path="${javac.classpath}"/> + </classpath> + <fileset dir="${src.dir}" excludes="${excludes}" includes="${includes}"> + <filename name="**/*.java"/> + </fileset> + <fileset dir="${build.generated.sources.dir}" erroronmissingdir="false"> + <include name="**/*.java"/> + </fileset> + </javadoc> + </target> + <target depends="init,-javadoc-build" if="netbeans.home" name="-javadoc-browse" unless="no.javadoc.preview"> + <nbbrowse file="${dist.javadoc.dir}/index.html"/> + </target> + <target depends="init,-javadoc-build,-javadoc-browse" description="Build Javadoc." name="javadoc"/> + <!-- + ========================= + JUNIT COMPILATION SECTION + ========================= + --> + <target depends="init,compile" if="have.tests" name="-pre-pre-compile-test"> + <mkdir dir="${build.test.classes.dir}"/> + </target> + <target name="-pre-compile-test"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target if="do.depend.true" name="-compile-test-depend"> + <j2seproject3:depend classpath="${javac.test.classpath}" destdir="${build.test.classes.dir}" srcdir="${test.src.dir}"/> + </target> + <target depends="init,compile,-pre-pre-compile-test,-pre-compile-test,-compile-test-depend" if="have.tests" name="-do-compile-test"> + <j2seproject3:javac classpath="${javac.test.classpath}" debug="true" destdir="${build.test.classes.dir}" srcdir="${test.src.dir}"/> + <copy todir="${build.test.classes.dir}"> + <fileset dir="${test.src.dir}" excludes="${build.classes.excludes},${excludes}" includes="${includes}"/> + </copy> + </target> + <target name="-post-compile-test"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,compile,-pre-pre-compile-test,-pre-compile-test,-do-compile-test,-post-compile-test" name="compile-test"/> + <target name="-pre-compile-test-single"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,compile,-pre-pre-compile-test,-pre-compile-test-single" if="have.tests" name="-do-compile-test-single"> + <fail unless="javac.includes">Must select some files in the IDE or set javac.includes</fail> + <j2seproject3:force-recompile destdir="${build.test.classes.dir}"/> + <j2seproject3:javac classpath="${javac.test.classpath}" debug="true" destdir="${build.test.classes.dir}" excludes="" includes="${javac.includes}" sourcepath="${test.src.dir}" srcdir="${test.src.dir}"/> + <copy todir="${build.test.classes.dir}"> + <fileset dir="${test.src.dir}" excludes="${build.classes.excludes},${excludes}" includes="${includes}"/> + </copy> + </target> + <target name="-post-compile-test-single"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,compile,-pre-pre-compile-test,-pre-compile-test-single,-do-compile-test-single,-post-compile-test-single" name="compile-test-single"/> + <!-- + ======================= + JUNIT EXECUTION SECTION + ======================= + --> + <target depends="init" if="have.tests" name="-pre-test-run"> + <mkdir dir="${build.test.results.dir}"/> + </target> + <target depends="init,compile-test,-pre-test-run" if="have.tests" name="-do-test-run"> + <j2seproject3:junit testincludes="**/*Test.java"/> + </target> + <target depends="init,compile-test,-pre-test-run,-do-test-run" if="have.tests" name="-post-test-run"> + <fail if="tests.failed" unless="ignore.failing.tests">Some tests failed; see details above.</fail> + </target> + <target depends="init" if="have.tests" name="test-report"/> + <target depends="init" if="netbeans.home+have.tests" name="-test-browse"/> + <target depends="init,compile-test,-pre-test-run,-do-test-run,test-report,-post-test-run,-test-browse" description="Run unit tests." name="test"/> + <target depends="init" if="have.tests" name="-pre-test-run-single"> + <mkdir dir="${build.test.results.dir}"/> + </target> + <target depends="init,compile-test-single,-pre-test-run-single" if="have.tests" name="-do-test-run-single"> + <fail unless="test.includes">Must select some files in the IDE or set test.includes</fail> + <j2seproject3:junit excludes="" includes="${test.includes}"/> + </target> + <target depends="init,compile-test-single,-pre-test-run-single,-do-test-run-single" if="have.tests" name="-post-test-run-single"> + <fail if="tests.failed" unless="ignore.failing.tests">Some tests failed; see details above.</fail> + </target> + <target depends="init,compile-test-single,-pre-test-run-single,-do-test-run-single,-post-test-run-single" description="Run single unit test." name="test-single"/> + <!-- + ======================= + JUNIT DEBUGGING SECTION + ======================= + --> + <target depends="init,compile-test" if="have.tests" name="-debug-start-debuggee-test"> + <fail unless="test.class">Must select one file in the IDE or set test.class</fail> + <property location="${build.test.results.dir}/TEST-${test.class}.xml" name="test.report.file"/> + <delete file="${test.report.file}"/> + <mkdir dir="${build.test.results.dir}"/> + <j2seproject3:debug classname="org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner" classpath="${ant.home}/lib/ant.jar:${ant.home}/lib/ant-junit.jar:${debug.test.classpath}"> + <customize> + <syspropertyset> + <propertyref prefix="test-sys-prop."/> + <mapper from="test-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + <arg value="${test.class}"/> + <arg value="showoutput=true"/> + <arg value="formatter=org.apache.tools.ant.taskdefs.optional.junit.BriefJUnitResultFormatter"/> + <arg value="formatter=org.apache.tools.ant.taskdefs.optional.junit.XMLJUnitResultFormatter,${test.report.file}"/> + </customize> + </j2seproject3:debug> + </target> + <target depends="init,compile-test" if="netbeans.home+have.tests" name="-debug-start-debugger-test"> + <j2seproject1:nbjpdastart classpath="${debug.test.classpath}" name="${test.class}"/> + </target> + <target depends="init,compile-test-single,-debug-start-debugger-test,-debug-start-debuggee-test" name="debug-test"/> + <target depends="init,-pre-debug-fix,compile-test-single" if="netbeans.home" name="-do-debug-fix-test"> + <j2seproject1:nbjpdareload dir="${build.test.classes.dir}"/> + </target> + <target depends="init,-pre-debug-fix,-do-debug-fix-test" if="netbeans.home" name="debug-fix-test"/> + <!-- + ========================= + APPLET EXECUTION SECTION + ========================= + --> + <target depends="init,compile-single" name="run-applet"> + <fail unless="applet.url">Must select one file in the IDE or set applet.url</fail> + <j2seproject1:java classname="sun.applet.AppletViewer"> + <customize> + <arg value="${applet.url}"/> + </customize> + </j2seproject1:java> + </target> + <!-- + ========================= + APPLET DEBUGGING SECTION + ========================= + --> + <target depends="init,compile-single" if="netbeans.home" name="-debug-start-debuggee-applet"> + <fail unless="applet.url">Must select one file in the IDE or set applet.url</fail> + <j2seproject3:debug classname="sun.applet.AppletViewer"> + <customize> + <arg value="${applet.url}"/> + </customize> + </j2seproject3:debug> + </target> + <target depends="init,compile-single,-debug-start-debugger,-debug-start-debuggee-applet" if="netbeans.home" name="debug-applet"/> + <!-- + =============== + CLEANUP SECTION + =============== + --> + <target name="-deps-clean-init" unless="built-clean.properties"> + <property location="${build.dir}/built-clean.properties" name="built-clean.properties"/> + <delete file="${built-clean.properties}" quiet="true"/> + </target> + <target if="already.built.clean.${basedir}" name="-warn-already-built-clean"> + <echo level="warn" message="Cycle detected: eye was already built"/> + </target> + <target depends="init,-deps-clean-init" name="deps-clean" unless="no.deps"> + <mkdir dir="${build.dir}"/> + <touch file="${built-clean.properties}" verbose="false"/> + <property file="${built-clean.properties}" prefix="already.built.clean."/> + <antcall target="-warn-already-built-clean"/> + <propertyfile file="${built-clean.properties}"> + <entry key="${basedir}" value=""/> + </propertyfile> + <antcall target="-maybe-call-dep"> + <param name="call.built.properties" value="${built-clean.properties}"/> + <param location="${project.DB4o-Server}" name="call.subproject"/> + <param location="${project.DB4o-Server}/build.xml" name="call.script"/> + <param name="call.target" value="clean"/> + <param name="transfer.built-clean.properties" value="${built-clean.properties}"/> + </antcall> + </target> + <target depends="init" name="-do-clean"> + <delete dir="${build.dir}"/> + <delete dir="${dist.dir}" followsymlinks="false" includeemptydirs="true"/> + </target> + <target name="-post-clean"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,deps-clean,-do-clean,-post-clean" description="Clean build products." name="clean"/> + <target name="-check-call-dep"> + <property file="${call.built.properties}" prefix="already.built."/> + <condition property="should.call.dep"> + <not> + <isset property="already.built.${call.subproject}"/> + </not> + </condition> + </target> + <target depends="-check-call-dep" if="should.call.dep" name="-maybe-call-dep"> + <ant antfile="${call.script}" inheritall="false" target="${call.target}"> + <propertyset> + <propertyref prefix="transfer."/> + <mapper from="transfer.*" to="*" type="glob"/> + </propertyset> + </ant> + </target> +</project> diff --git a/nbproject/.svn/text-base/genfiles.properties.svn-base b/nbproject/.svn/text-base/genfiles.properties.svn-base new file mode 100644 index 0000000..b1f8948 --- /dev/null +++ b/nbproject/.svn/text-base/genfiles.properties.svn-base @@ -0,0 +1,8 @@ +build.xml.data.CRC32=c7637cc6 +build.xml.script.CRC32=809b2dff [email protected] +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=c7637cc6 +nbproject/build-impl.xml.script.CRC32=040939fe +nbproject/[email protected] diff --git a/nbproject/.svn/text-base/project.properties.svn-base b/nbproject/.svn/text-base/project.properties.svn-base new file mode 100644 index 0000000..2b08b75 --- /dev/null +++ b/nbproject/.svn/text-base/project.properties.svn-base @@ -0,0 +1,73 @@ +application.title=eye +application.vendor=Admin +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +build.generated.sources.dir=${build.dir}/generated-sources +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +# Uncomment to specify the preferred debugger connection transport: +#debug.transport=dt_socket +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/eye.jar +dist.javadoc.dir=${dist.dir}/javadoc +endorsed.classpath= +excludes= +file.reference.db4o-7.12.145.14409-all-java5.jar=../DB4o-Server/libs/db4o-7.12.145.14409-all-java5.jar +file.reference.log4j-1.2.15.jar=libs\\log4j-1.2.15.jar +includes=** +jar.compress=false +javac.classpath=\ + ${reference.DB4o-Server.jar}:\ + ${file.reference.log4j-1.2.15.jar}:\ + ${file.reference.db4o-7.12.145.14409-all-java5.jar} +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.source=1.5 +javac.target=1.5 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir}:\ + ${libs.junit.classpath}:\ + ${libs.junit_4.classpath} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding=${source.encoding} +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +jaxbwiz.endorsed.dirs="${netbeans.home}/../ide12/modules/ext/jaxb/api" +main.class=eye.Eye +manifest.file=manifest.mf +meta.inf.dir=${src.dir}/META-INF +platform.active=default_platform +project.DB4o-Server=../DB4o-Server +reference.DB4o-Server.jar=${project.DB4o-Server}/dist/DB4o-Server.jar +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value +# or test-sys-prop.name=value to set system properties for unit tests): +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +source.encoding=UTF-8 +src.dir=src +test.src.dir=test diff --git a/nbproject/.svn/text-base/project.xml.svn-base b/nbproject/.svn/text-base/project.xml.svn-base new file mode 100644 index 0000000..24b7095 --- /dev/null +++ b/nbproject/.svn/text-base/project.xml.svn-base @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://www.netbeans.org/ns/project/1"> + <type>org.netbeans.modules.java.j2seproject</type> + <configuration> + <data xmlns="http://www.netbeans.org/ns/j2se-project/3"> + <name>eye</name> + <source-roots> + <root id="src.dir"/> + </source-roots> + <test-roots> + <root id="test.src.dir"/> + </test-roots> + </data> + <references xmlns="http://www.netbeans.org/ns/ant-project-references/1"> + <reference> + <foreign-project>DB4o-Server</foreign-project> + <artifact-type>jar</artifact-type> + <script>build.xml</script> + <target>jar</target> + <clean-target>clean</clean-target> + <id>jar</id> + </reference> + </references> + </configuration> +</project> diff --git a/nbproject/build-impl.xml b/nbproject/build-impl.xml new file mode 100644 index 0000000..e5f30a8 --- /dev/null +++ b/nbproject/build-impl.xml @@ -0,0 +1,819 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- +*** GENERATED FROM project.xml - DO NOT EDIT *** +*** EDIT ../build.xml INSTEAD *** + +For the purpose of easier reading the script +is divided into following sections: + + - initialization + - compilation + - jar + - execution + - debugging + - javadoc + - junit compilation + - junit execution + - junit debugging + - applet + - cleanup + + --> +<project xmlns:j2seproject1="http://www.netbeans.org/ns/j2se-project/1" xmlns:j2seproject3="http://www.netbeans.org/ns/j2se-project/3" xmlns:jaxrpc="http://www.netbeans.org/ns/j2se-project/jax-rpc" basedir=".." default="default" name="eye-impl"> + <fail message="Please build using Ant 1.7.1 or higher."> + <condition> + <not> + <antversion atleast="1.7.1"/> + </not> + </condition> + </fail> + <target depends="test,jar,javadoc" description="Build and test whole project." name="default"/> + <!-- + ====================== + INITIALIZATION SECTION + ====================== + --> + <target name="-pre-init"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="-pre-init" name="-init-private"> + <property file="nbproject/private/config.properties"/> + <property file="nbproject/private/configs/${config}.properties"/> + <property file="nbproject/private/private.properties"/> + </target> + <target depends="-pre-init,-init-private" name="-init-user"> + <property file="${user.properties.file}"/> + <!-- The two properties below are usually overridden --> + <!-- by the active platform. Just a fallback. --> + <property name="default.javac.source" value="1.4"/> + <property name="default.javac.target" value="1.4"/> + </target> + <target depends="-pre-init,-init-private,-init-user" name="-init-project"> + <property file="nbproject/configs/${config}.properties"/> + <property file="nbproject/project.properties"/> + </target> + <target depends="-pre-init,-init-private,-init-user,-init-project,-init-macrodef-property" name="-do-init"> + <available file="${manifest.file}" property="manifest.available"/> + <condition property="main.class.available"> + <and> + <isset property="main.class"/> + <not> + <equals arg1="${main.class}" arg2="" trim="true"/> + </not> + </and> + </condition> + <condition property="manifest.available+main.class"> + <and> + <isset property="manifest.available"/> + <isset property="main.class.available"/> + </and> + </condition> + <condition property="do.mkdist"> + <and> + <isset property="libs.CopyLibs.classpath"/> + <not> + <istrue value="${mkdist.disabled}"/> + </not> + </and> + </condition> + <condition property="manifest.available+main.class+mkdist.available"> + <and> + <istrue value="${manifest.available+main.class}"/> + <isset property="do.mkdist"/> + </and> + </condition> + <condition property="manifest.available+mkdist.available"> + <and> + <istrue value="${manifest.available}"/> + <isset property="do.mkdist"/> + </and> + </condition> + <condition property="manifest.available-mkdist.available"> + <or> + <istrue value="${manifest.available}"/> + <isset property="do.mkdist"/> + </or> + </condition> + <condition property="manifest.available+main.class-mkdist.available"> + <or> + <istrue value="${manifest.available+main.class}"/> + <isset property="do.mkdist"/> + </or> + </condition> + <condition property="have.tests"> + <or> + <available file="${test.src.dir}"/> + </or> + </condition> + <condition property="have.sources"> + <or> + <available file="${src.dir}"/> + </or> + </condition> + <condition property="netbeans.home+have.tests"> + <and> + <isset property="netbeans.home"/> + <isset property="have.tests"/> + </and> + </condition> + <condition property="no.javadoc.preview"> + <and> + <isset property="javadoc.preview"/> + <isfalse value="${javadoc.preview}"/> + </and> + </condition> + <property name="run.jvmargs" value=""/> + <property name="javac.compilerargs" value=""/> + <property name="work.dir" value="${basedir}"/> + <condition property="no.deps"> + <and> + <istrue value="${no.dependencies}"/> + </and> + </condition> + <property name="javac.debug" value="true"/> + <property name="javadoc.preview" value="true"/> + <property name="application.args" value=""/> + <property name="source.encoding" value="${file.encoding}"/> + <property name="runtime.encoding" value="${source.encoding}"/> + <condition property="javadoc.encoding.used" value="${javadoc.encoding}"> + <and> + <isset property="javadoc.encoding"/> + <not> + <equals arg1="${javadoc.encoding}" arg2=""/> + </not> + </and> + </condition> + <property name="javadoc.encoding.used" value="${source.encoding}"/> + <property name="includes" value="**"/> + <property name="excludes" value=""/> + <property name="do.depend" value="false"/> + <condition property="do.depend.true"> + <istrue value="${do.depend}"/> + </condition> + <path id="endorsed.classpath.path" path="${endorsed.classpath}"/> + <condition else="" property="endorsed.classpath.cmd.line.arg" value="-Xbootclasspath/p:'${toString:endorsed.classpath.path}'"> + <length length="0" string="${endorsed.classpath}" when="greater"/> + </condition> + <property name="javac.fork" value="false"/> + </target> + <target name="-post-init"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="-pre-init,-init-private,-init-user,-init-project,-do-init" name="-init-check"> + <fail unless="src.dir">Must set src.dir</fail> + <fail unless="test.src.dir">Must set test.src.dir</fail> + <fail unless="build.dir">Must set build.dir</fail> + <fail unless="dist.dir">Must set dist.dir</fail> + <fail unless="build.classes.dir">Must set build.classes.dir</fail> + <fail unless="dist.javadoc.dir">Must set dist.javadoc.dir</fail> + <fail unless="build.test.classes.dir">Must set build.test.classes.dir</fail> + <fail unless="build.test.results.dir">Must set build.test.results.dir</fail> + <fail unless="build.classes.excludes">Must set build.classes.excludes</fail> + <fail unless="dist.jar">Must set dist.jar</fail> + </target> + <target name="-init-macrodef-property"> + <macrodef name="property" uri="http://www.netbeans.org/ns/j2se-project/1"> + <attribute name="name"/> + <attribute name="value"/> + <sequential> + <property name="@{name}" value="${@{value}}"/> + </sequential> + </macrodef> + </target> + <target name="-init-macrodef-javac"> + <macrodef name="javac" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${src.dir}" name="srcdir"/> + <attribute default="${build.classes.dir}" name="destdir"/> + <attribute default="${javac.classpath}" name="classpath"/> + <attribute default="${includes}" name="includes"/> + <attribute default="${excludes}" name="excludes"/> + <attribute default="${javac.debug}" name="debug"/> + <attribute default="${empty.dir}" name="sourcepath"/> + <attribute default="${empty.dir}" name="gensrcdir"/> + <element name="customize" optional="true"/> + <sequential> + <property location="${build.dir}/empty" name="empty.dir"/> + <mkdir dir="${empty.dir}"/> + <javac debug="@{debug}" deprecation="${javac.deprecation}" destdir="@{destdir}" encoding="${source.encoding}" excludes="@{excludes}" fork="${javac.fork}" includeantruntime="false" includes="@{includes}" source="${javac.source}" sourcepath="@{sourcepath}" srcdir="@{srcdir}" target="${javac.target}" tempdir="${java.io.tmpdir}"> + <src> + <dirset dir="@{gensrcdir}" erroronmissingdir="false"> + <include name="*"/> + </dirset> + </src> + <classpath> + <path path="@{classpath}"/> + </classpath> + <compilerarg line="${endorsed.classpath.cmd.line.arg}"/> + <compilerarg line="${javac.compilerargs}"/> + <customize/> + </javac> + </sequential> + </macrodef> + <macrodef name="depend" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${src.dir}" name="srcdir"/> + <attribute default="${build.classes.dir}" name="destdir"/> + <attribute default="${javac.classpath}" name="classpath"/> + <sequential> + <depend cache="${build.dir}/depcache" destdir="@{destdir}" excludes="${excludes}" includes="${includes}" srcdir="@{srcdir}"> + <classpath> + <path path="@{classpath}"/> + </classpath> + </depend> + </sequential> + </macrodef> + <macrodef name="force-recompile" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${build.classes.dir}" name="destdir"/> + <sequential> + <fail unless="javac.includes">Must set javac.includes</fail> + <pathconvert pathsep="," property="javac.includes.binary"> + <path> + <filelist dir="@{destdir}" files="${javac.includes}"/> + </path> + <globmapper from="*.java" to="*.class"/> + </pathconvert> + <delete> + <files includes="${javac.includes.binary}"/> + </delete> + </sequential> + </macrodef> + </target> + <target name="-init-macrodef-junit"> + <macrodef name="junit" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${includes}" name="includes"/> + <attribute default="${excludes}" name="excludes"/> + <attribute default="**" name="testincludes"/> + <sequential> + <junit dir="${work.dir}" errorproperty="tests.failed" failureproperty="tests.failed" fork="true" showoutput="true" tempdir="${build.dir}"> + <batchtest todir="${build.test.results.dir}"> + <fileset dir="${test.src.dir}" excludes="@{excludes},${excludes}" includes="@{includes}"> + <filename name="@{testincludes}"/> + </fileset> + </batchtest> + <classpath> + <path path="${run.test.classpath}"/> + </classpath> + <syspropertyset> + <propertyref prefix="test-sys-prop."/> + <mapper from="test-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + <formatter type="brief" usefile="false"/> + <formatter type="xml"/> + <jvmarg line="${endorsed.classpath.cmd.line.arg}"/> + <jvmarg line="${run.jvmargs}"/> + </junit> + </sequential> + </macrodef> + </target> + <target depends="-init-debug-args" name="-init-macrodef-nbjpda"> + <macrodef name="nbjpdastart" uri="http://www.netbeans.org/ns/j2se-project/1"> + <attribute default="${main.class}" name="name"/> + <attribute default="${debug.classpath}" name="classpath"/> + <attribute default="" name="stopclassname"/> + <sequential> + <nbjpdastart addressproperty="jpda.address" name="@{name}" stopclassname="@{stopclassname}" transport="${debug-transport}"> + <classpath> + <path path="@{classpath}"/> + </classpath> + </nbjpdastart> + </sequential> + </macrodef> + <macrodef name="nbjpdareload" uri="http://www.netbeans.org/ns/j2se-project/1"> + <attribute default="${build.classes.dir}" name="dir"/> + <sequential> + <nbjpdareload> + <fileset dir="@{dir}" includes="${fix.classes}"> + <include name="${fix.includes}*.class"/> + </fileset> + </nbjpdareload> + </sequential> + </macrodef> + </target> + <target name="-init-debug-args"> + <property name="version-output" value="java version &quot;${ant.java.version}"/> + <condition property="have-jdk-older-than-1.4"> + <or> + <contains string="${version-output}" substring="java version &quot;1.0"/> + <contains string="${version-output}" substring="java version &quot;1.1"/> + <contains string="${version-output}" substring="java version &quot;1.2"/> + <contains string="${version-output}" substring="java version &quot;1.3"/> + </or> + </condition> + <condition else="-Xdebug" property="debug-args-line" value="-Xdebug -Xnoagent -Djava.compiler=none"> + <istrue value="${have-jdk-older-than-1.4}"/> + </condition> + <condition else="dt_socket" property="debug-transport-by-os" value="dt_shmem"> + <os family="windows"/> + </condition> + <condition else="${debug-transport-by-os}" property="debug-transport" value="${debug.transport}"> + <isset property="debug.transport"/> + </condition> + </target> + <target depends="-init-debug-args" name="-init-macrodef-debug"> + <macrodef name="debug" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${main.class}" name="classname"/> + <attribute default="${debug.classpath}" name="classpath"/> + <element name="customize" optional="true"/> + <sequential> + <java classname="@{classname}" dir="${work.dir}" fork="true"> + <jvmarg line="${endorsed.classpath.cmd.line.arg}"/> + <jvmarg line="${debug-args-line}"/> + <jvmarg value="-Xrunjdwp:transport=${debug-transport},address=${jpda.address}"/> + <jvmarg value="-Dfile.encoding=${runtime.encoding}"/> + <redirector errorencoding="${runtime.encoding}" inputencoding="${runtime.encoding}" outputencoding="${runtime.encoding}"/> + <jvmarg line="${run.jvmargs}"/> + <classpath> + <path path="@{classpath}"/> + </classpath> + <syspropertyset> + <propertyref prefix="run-sys-prop."/> + <mapper from="run-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + <customize/> + </java> + </sequential> + </macrodef> + </target> + <target name="-init-macrodef-java"> + <macrodef name="java" uri="http://www.netbeans.org/ns/j2se-project/1"> + <attribute default="${main.class}" name="classname"/> + <attribute default="${run.classpath}" name="classpath"/> + <element name="customize" optional="true"/> + <sequential> + <java classname="@{classname}" dir="${work.dir}" fork="true"> + <jvmarg line="${endorsed.classpath.cmd.line.arg}"/> + <jvmarg value="-Dfile.encoding=${runtime.encoding}"/> + <redirector errorencoding="${runtime.encoding}" inputencoding="${runtime.encoding}" outputencoding="${runtime.encoding}"/> + <jvmarg line="${run.jvmargs}"/> + <classpath> + <path path="@{classpath}"/> + </classpath> + <syspropertyset> + <propertyref prefix="run-sys-prop."/> + <mapper from="run-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + <customize/> + </java> + </sequential> + </macrodef> + </target> + <target name="-init-presetdef-jar"> + <presetdef name="jar" uri="http://www.netbeans.org/ns/j2se-project/1"> + <jar compress="${jar.compress}" jarfile="${dist.jar}"> + <j2seproject1:fileset dir="${build.classes.dir}"/> + </jar> + </presetdef> + </target> + <target depends="-pre-init,-init-private,-init-user,-init-project,-do-init,-post-init,-init-check,-init-macrodef-property,-init-macrodef-javac,-init-macrodef-junit,-init-macrodef-nbjpda,-init-macrodef-debug,-init-macrodef-java,-init-presetdef-jar" name="init"/> + <!-- + =================== + COMPILATION SECTION + =================== + --> + <target name="-deps-jar-init" unless="built-jar.properties"> + <property location="${build.dir}/built-jar.properties" name="built-jar.properties"/> + <delete file="${built-jar.properties}" quiet="true"/> + </target> + <target if="already.built.jar.${basedir}" name="-warn-already-built-jar"> + <echo level="warn" message="Cycle detected: eye was already built"/> + </target> + <target depends="init,-deps-jar-init" name="deps-jar" unless="no.deps"> + <mkdir dir="${build.dir}"/> + <touch file="${built-jar.properties}" verbose="false"/> + <property file="${built-jar.properties}" prefix="already.built.jar."/> + <antcall target="-warn-already-built-jar"/> + <propertyfile file="${built-jar.properties}"> + <entry key="${basedir}" value=""/> + </propertyfile> + <antcall target="-maybe-call-dep"> + <param name="call.built.properties" value="${built-jar.properties}"/> + <param location="${project.DB4o-Server}" name="call.subproject"/> + <param location="${project.DB4o-Server}/build.xml" name="call.script"/> + <param name="call.target" value="jar"/> + <param name="transfer.built-jar.properties" value="${built-jar.properties}"/> + </antcall> + </target> + <target depends="init,-check-automatic-build,-clean-after-automatic-build" name="-verify-automatic-build"/> + <target depends="init" name="-check-automatic-build"> + <available file="${build.classes.dir}/.netbeans_automatic_build" property="netbeans.automatic.build"/> + </target> + <target depends="init" if="netbeans.automatic.build" name="-clean-after-automatic-build"> + <antcall target="clean"/> + </target> + <target depends="init,deps-jar" name="-pre-pre-compile"> + <mkdir dir="${build.classes.dir}"/> + </target> + <target name="-pre-compile"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target if="do.depend.true" name="-compile-depend"> + <pathconvert property="build.generated.subdirs"> + <dirset dir="${build.generated.sources.dir}" erroronmissingdir="false"> + <include name="*"/> + </dirset> + </pathconvert> + <j2seproject3:depend srcdir="${src.dir}:${build.generated.subdirs}"/> + </target> + <target depends="init,deps-jar,-pre-pre-compile,-pre-compile,-compile-depend" if="have.sources" name="-do-compile"> + <j2seproject3:javac gensrcdir="${build.generated.sources.dir}"/> + <copy todir="${build.classes.dir}"> + <fileset dir="${src.dir}" excludes="${build.classes.excludes},${excludes}" includes="${includes}"/> + </copy> + </target> + <target name="-post-compile"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,deps-jar,-verify-automatic-build,-pre-pre-compile,-pre-compile,-do-compile,-post-compile" description="Compile project." name="compile"/> + <target name="-pre-compile-single"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,deps-jar,-pre-pre-compile" name="-do-compile-single"> + <fail unless="javac.includes">Must select some files in the IDE or set javac.includes</fail> + <j2seproject3:force-recompile/> + <j2seproject3:javac excludes="" gensrcdir="${build.generated.sources.dir}" includes="${javac.includes}" sourcepath="${src.dir}"/> + </target> + <target name="-post-compile-single"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,deps-jar,-verify-automatic-build,-pre-pre-compile,-pre-compile-single,-do-compile-single,-post-compile-single" name="compile-single"/> + <!-- + ==================== + JAR BUILDING SECTION + ==================== + --> + <target depends="init" name="-pre-pre-jar"> + <dirname file="${dist.jar}" property="dist.jar.dir"/> + <mkdir dir="${dist.jar.dir}"/> + </target> + <target name="-pre-jar"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,compile,-pre-pre-jar,-pre-jar" name="-do-jar-without-manifest" unless="manifest.available-mkdist.available"> + <j2seproject1:jar/> + </target> + <target depends="init,compile,-pre-pre-jar,-pre-jar" if="manifest.available" name="-do-jar-with-manifest" unless="manifest.available+main.class-mkdist.available"> + <j2seproject1:jar manifest="${manifest.file}"/> + </target> + <target depends="init,compile,-pre-pre-jar,-pre-jar" if="manifest.available+main.class" name="-do-jar-with-mainclass" unless="manifest.available+main.class+mkdist.available"> + <j2seproject1:jar manifest="${manifest.file}"> + <j2seproject1:manifest> + <j2seproject1:attribute name="Main-Class" value="${main.class}"/> + </j2seproject1:manifest> + </j2seproject1:jar> + <echo>To run this application from the command line without Ant, try:</echo> + <property location="${build.classes.dir}" name="build.classes.dir.resolved"/> + <property location="${dist.jar}" name="dist.jar.resolved"/> + <pathconvert property="run.classpath.with.dist.jar"> + <path path="${run.classpath}"/> + <map from="${build.classes.dir.resolved}" to="${dist.jar.resolved}"/> + </pathconvert> + <echo>java -cp "${run.classpath.with.dist.jar}" ${main.class}</echo> + </target> + <target depends="init,compile,-pre-pre-jar,-pre-jar" if="manifest.available+main.class+mkdist.available" name="-do-jar-with-libraries"> + <property location="${build.classes.dir}" name="build.classes.dir.resolved"/> + <pathconvert property="run.classpath.without.build.classes.dir"> + <path path="${run.classpath}"/> + <map from="${build.classes.dir.resolved}" to=""/> + </pathconvert> + <pathconvert pathsep=" " property="jar.classpath"> + <path path="${run.classpath.without.build.classes.dir}"/> + <chainedmapper> + <flattenmapper/> + <globmapper from="*" to="lib/*"/> + </chainedmapper> + </pathconvert> + <taskdef classname="org.netbeans.modules.java.j2seproject.copylibstask.CopyLibs" classpath="${libs.CopyLibs.classpath}" name="copylibs"/> + <copylibs compress="${jar.compress}" jarfile="${dist.jar}" manifest="${manifest.file}" runtimeclasspath="${run.classpath.without.build.classes.dir}"> + <fileset dir="${build.classes.dir}"/> + <manifest> + <attribute name="Main-Class" value="${main.class}"/> + <attribute name="Class-Path" value="${jar.classpath}"/> + </manifest> + </copylibs> + <echo>To run this application from the command line without Ant, try:</echo> + <property location="${dist.jar}" name="dist.jar.resolved"/> + <echo>java -jar "${dist.jar.resolved}"</echo> + </target> + <target depends="init,compile,-pre-pre-jar,-pre-jar" if="manifest.available+mkdist.available" name="-do-jar-with-libraries-without-mainclass" unless="main.class.available"> + <property location="${build.classes.dir}" name="build.classes.dir.resolved"/> + <pathconvert property="run.classpath.without.build.classes.dir"> + <path path="${run.classpath}"/> + <map from="${build.classes.dir.resolved}" to=""/> + </pathconvert> + <pathconvert pathsep=" " property="jar.classpath"> + <path path="${run.classpath.without.build.classes.dir}"/> + <chainedmapper> + <flattenmapper/> + <globmapper from="*" to="lib/*"/> + </chainedmapper> + </pathconvert> + <taskdef classname="org.netbeans.modules.java.j2seproject.copylibstask.CopyLibs" classpath="${libs.CopyLibs.classpath}" name="copylibs"/> + <copylibs compress="${jar.compress}" jarfile="${dist.jar}" manifest="${manifest.file}" runtimeclasspath="${run.classpath.without.build.classes.dir}"> + <fileset dir="${build.classes.dir}"/> + <manifest> + <attribute name="Class-Path" value="${jar.classpath}"/> + </manifest> + </copylibs> + </target> + <target depends="init,compile,-pre-pre-jar,-pre-jar" if="do.mkdist" name="-do-jar-with-libraries-without-manifest" unless="manifest.available"> + <property location="${build.classes.dir}" name="build.classes.dir.resolved"/> + <pathconvert property="run.classpath.without.build.classes.dir"> + <path path="${run.classpath}"/> + <map from="${build.classes.dir.resolved}" to=""/> + </pathconvert> + <pathconvert pathsep=" " property="jar.classpath"> + <path path="${run.classpath.without.build.classes.dir}"/> + <chainedmapper> + <flattenmapper/> + <globmapper from="*" to="lib/*"/> + </chainedmapper> + </pathconvert> + <taskdef classname="org.netbeans.modules.java.j2seproject.copylibstask.CopyLibs" classpath="${libs.CopyLibs.classpath}" name="copylibs"/> + <copylibs compress="${jar.compress}" jarfile="${dist.jar}" runtimeclasspath="${run.classpath.without.build.classes.dir}"> + <fileset dir="${build.classes.dir}"/> + <manifest> + <attribute name="Class-Path" value="${jar.classpath}"/> + </manifest> + </copylibs> + </target> + <target name="-post-jar"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,compile,-pre-jar,-do-jar-with-manifest,-do-jar-without-manifest,-do-jar-with-mainclass,-do-jar-with-libraries,-do-jar-with-libraries-without-mainclass,-do-jar-with-libraries-without-manifest,-post-jar" description="Build JAR." name="jar"/> + <!-- + ================= + EXECUTION SECTION + ================= + --> + <target depends="init,compile" description="Run a main class." name="run"> + <j2seproject1:java> + <customize> + <arg line="${application.args}"/> + </customize> + </j2seproject1:java> + </target> + <target name="-do-not-recompile"> + <property name="javac.includes.binary" value=""/> + </target> + <target depends="init,compile-single" name="run-single"> + <fail unless="run.class">Must select one file in the IDE or set run.class</fail> + <j2seproject1:java classname="${run.class}"/> + </target> + <target depends="init,compile-test-single" name="run-test-with-main"> + <fail unless="run.class">Must select one file in the IDE or set run.class</fail> + <j2seproject1:java classname="${run.class}" classpath="${run.test.classpath}"/> + </target> + <!-- + ================= + DEBUGGING SECTION + ================= + --> + <target depends="init" if="netbeans.home" name="-debug-start-debugger"> + <j2seproject1:nbjpdastart name="${debug.class}"/> + </target> + <target depends="init" if="netbeans.home" name="-debug-start-debugger-main-test"> + <j2seproject1:nbjpdastart classpath="${debug.test.classpath}" name="${debug.class}"/> + </target> + <target depends="init,compile" name="-debug-start-debuggee"> + <j2seproject3:debug> + <customize> + <arg line="${application.args}"/> + </customize> + </j2seproject3:debug> + </target> + <target depends="init,compile,-debug-start-debugger,-debug-start-debuggee" description="Debug project in IDE." if="netbeans.home" name="debug"/> + <target depends="init" if="netbeans.home" name="-debug-start-debugger-stepinto"> + <j2seproject1:nbjpdastart stopclassname="${main.class}"/> + </target> + <target depends="init,compile,-debug-start-debugger-stepinto,-debug-start-debuggee" if="netbeans.home" name="debug-stepinto"/> + <target depends="init,compile-single" if="netbeans.home" name="-debug-start-debuggee-single"> + <fail unless="debug.class">Must select one file in the IDE or set debug.class</fail> + <j2seproject3:debug classname="${debug.class}"/> + </target> + <target depends="init,compile-single,-debug-start-debugger,-debug-start-debuggee-single" if="netbeans.home" name="debug-single"/> + <target depends="init,compile-test-single" if="netbeans.home" name="-debug-start-debuggee-main-test"> + <fail unless="debug.class">Must select one file in the IDE or set debug.class</fail> + <j2seproject3:debug classname="${debug.class}" classpath="${debug.test.classpath}"/> + </target> + <target depends="init,compile-test-single,-debug-start-debugger-main-test,-debug-start-debuggee-main-test" if="netbeans.home" name="debug-test-with-main"/> + <target depends="init" name="-pre-debug-fix"> + <fail unless="fix.includes">Must set fix.includes</fail> + <property name="javac.includes" value="${fix.includes}.java"/> + </target> + <target depends="init,-pre-debug-fix,compile-single" if="netbeans.home" name="-do-debug-fix"> + <j2seproject1:nbjpdareload/> + </target> + <target depends="init,-pre-debug-fix,-do-debug-fix" if="netbeans.home" name="debug-fix"/> + <!-- + =============== + JAVADOC SECTION + =============== + --> + <target depends="init" name="-javadoc-build"> + <mkdir dir="${dist.javadoc.dir}"/> + <javadoc additionalparam="${javadoc.additionalparam}" author="${javadoc.author}" charset="UTF-8" destdir="${dist.javadoc.dir}" docencoding="UTF-8" encoding="${javadoc.encoding.used}" failonerror="true" noindex="${javadoc.noindex}" nonavbar="${javadoc.nonavbar}" notree="${javadoc.notree}" private="${javadoc.private}" source="${javac.source}" splitindex="${javadoc.splitindex}" use="${javadoc.use}" useexternalfile="true" version="${javadoc.version}" windowtitle="${javadoc.windowtitle}"> + <classpath> + <path path="${javac.classpath}"/> + </classpath> + <fileset dir="${src.dir}" excludes="${excludes}" includes="${includes}"> + <filename name="**/*.java"/> + </fileset> + <fileset dir="${build.generated.sources.dir}" erroronmissingdir="false"> + <include name="**/*.java"/> + </fileset> + </javadoc> + </target> + <target depends="init,-javadoc-build" if="netbeans.home" name="-javadoc-browse" unless="no.javadoc.preview"> + <nbbrowse file="${dist.javadoc.dir}/index.html"/> + </target> + <target depends="init,-javadoc-build,-javadoc-browse" description="Build Javadoc." name="javadoc"/> + <!-- + ========================= + JUNIT COMPILATION SECTION + ========================= + --> + <target depends="init,compile" if="have.tests" name="-pre-pre-compile-test"> + <mkdir dir="${build.test.classes.dir}"/> + </target> + <target name="-pre-compile-test"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target if="do.depend.true" name="-compile-test-depend"> + <j2seproject3:depend classpath="${javac.test.classpath}" destdir="${build.test.classes.dir}" srcdir="${test.src.dir}"/> + </target> + <target depends="init,compile,-pre-pre-compile-test,-pre-compile-test,-compile-test-depend" if="have.tests" name="-do-compile-test"> + <j2seproject3:javac classpath="${javac.test.classpath}" debug="true" destdir="${build.test.classes.dir}" srcdir="${test.src.dir}"/> + <copy todir="${build.test.classes.dir}"> + <fileset dir="${test.src.dir}" excludes="${build.classes.excludes},${excludes}" includes="${includes}"/> + </copy> + </target> + <target name="-post-compile-test"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,compile,-pre-pre-compile-test,-pre-compile-test,-do-compile-test,-post-compile-test" name="compile-test"/> + <target name="-pre-compile-test-single"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,compile,-pre-pre-compile-test,-pre-compile-test-single" if="have.tests" name="-do-compile-test-single"> + <fail unless="javac.includes">Must select some files in the IDE or set javac.includes</fail> + <j2seproject3:force-recompile destdir="${build.test.classes.dir}"/> + <j2seproject3:javac classpath="${javac.test.classpath}" debug="true" destdir="${build.test.classes.dir}" excludes="" includes="${javac.includes}" sourcepath="${test.src.dir}" srcdir="${test.src.dir}"/> + <copy todir="${build.test.classes.dir}"> + <fileset dir="${test.src.dir}" excludes="${build.classes.excludes},${excludes}" includes="${includes}"/> + </copy> + </target> + <target name="-post-compile-test-single"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,compile,-pre-pre-compile-test,-pre-compile-test-single,-do-compile-test-single,-post-compile-test-single" name="compile-test-single"/> + <!-- + ======================= + JUNIT EXECUTION SECTION + ======================= + --> + <target depends="init" if="have.tests" name="-pre-test-run"> + <mkdir dir="${build.test.results.dir}"/> + </target> + <target depends="init,compile-test,-pre-test-run" if="have.tests" name="-do-test-run"> + <j2seproject3:junit testincludes="**/*Test.java"/> + </target> + <target depends="init,compile-test,-pre-test-run,-do-test-run" if="have.tests" name="-post-test-run"> + <fail if="tests.failed" unless="ignore.failing.tests">Some tests failed; see details above.</fail> + </target> + <target depends="init" if="have.tests" name="test-report"/> + <target depends="init" if="netbeans.home+have.tests" name="-test-browse"/> + <target depends="init,compile-test,-pre-test-run,-do-test-run,test-report,-post-test-run,-test-browse" description="Run unit tests." name="test"/> + <target depends="init" if="have.tests" name="-pre-test-run-single"> + <mkdir dir="${build.test.results.dir}"/> + </target> + <target depends="init,compile-test-single,-pre-test-run-single" if="have.tests" name="-do-test-run-single"> + <fail unless="test.includes">Must select some files in the IDE or set test.includes</fail> + <j2seproject3:junit excludes="" includes="${test.includes}"/> + </target> + <target depends="init,compile-test-single,-pre-test-run-single,-do-test-run-single" if="have.tests" name="-post-test-run-single"> + <fail if="tests.failed" unless="ignore.failing.tests">Some tests failed; see details above.</fail> + </target> + <target depends="init,compile-test-single,-pre-test-run-single,-do-test-run-single,-post-test-run-single" description="Run single unit test." name="test-single"/> + <!-- + ======================= + JUNIT DEBUGGING SECTION + ======================= + --> + <target depends="init,compile-test" if="have.tests" name="-debug-start-debuggee-test"> + <fail unless="test.class">Must select one file in the IDE or set test.class</fail> + <property location="${build.test.results.dir}/TEST-${test.class}.xml" name="test.report.file"/> + <delete file="${test.report.file}"/> + <mkdir dir="${build.test.results.dir}"/> + <j2seproject3:debug classname="org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner" classpath="${ant.home}/lib/ant.jar:${ant.home}/lib/ant-junit.jar:${debug.test.classpath}"> + <customize> + <syspropertyset> + <propertyref prefix="test-sys-prop."/> + <mapper from="test-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + <arg value="${test.class}"/> + <arg value="showoutput=true"/> + <arg value="formatter=org.apache.tools.ant.taskdefs.optional.junit.BriefJUnitResultFormatter"/> + <arg value="formatter=org.apache.tools.ant.taskdefs.optional.junit.XMLJUnitResultFormatter,${test.report.file}"/> + </customize> + </j2seproject3:debug> + </target> + <target depends="init,compile-test" if="netbeans.home+have.tests" name="-debug-start-debugger-test"> + <j2seproject1:nbjpdastart classpath="${debug.test.classpath}" name="${test.class}"/> + </target> + <target depends="init,compile-test-single,-debug-start-debugger-test,-debug-start-debuggee-test" name="debug-test"/> + <target depends="init,-pre-debug-fix,compile-test-single" if="netbeans.home" name="-do-debug-fix-test"> + <j2seproject1:nbjpdareload dir="${build.test.classes.dir}"/> + </target> + <target depends="init,-pre-debug-fix,-do-debug-fix-test" if="netbeans.home" name="debug-fix-test"/> + <!-- + ========================= + APPLET EXECUTION SECTION + ========================= + --> + <target depends="init,compile-single" name="run-applet"> + <fail unless="applet.url">Must select one file in the IDE or set applet.url</fail> + <j2seproject1:java classname="sun.applet.AppletViewer"> + <customize> + <arg value="${applet.url}"/> + </customize> + </j2seproject1:java> + </target> + <!-- + ========================= + APPLET DEBUGGING SECTION + ========================= + --> + <target depends="init,compile-single" if="netbeans.home" name="-debug-start-debuggee-applet"> + <fail unless="applet.url">Must select one file in the IDE or set applet.url</fail> + <j2seproject3:debug classname="sun.applet.AppletViewer"> + <customize> + <arg value="${applet.url}"/> + </customize> + </j2seproject3:debug> + </target> + <target depends="init,compile-single,-debug-start-debugger,-debug-start-debuggee-applet" if="netbeans.home" name="debug-applet"/> + <!-- + =============== + CLEANUP SECTION + =============== + --> + <target name="-deps-clean-init" unless="built-clean.properties"> + <property location="${build.dir}/built-clean.properties" name="built-clean.properties"/> + <delete file="${built-clean.properties}" quiet="true"/> + </target> + <target if="already.built.clean.${basedir}" name="-warn-already-built-clean"> + <echo level="warn" message="Cycle detected: eye was already built"/> + </target> + <target depends="init,-deps-clean-init" name="deps-clean" unless="no.deps"> + <mkdir dir="${build.dir}"/> + <touch file="${built-clean.properties}" verbose="false"/> + <property file="${built-clean.properties}" prefix="already.built.clean."/> + <antcall target="-warn-already-built-clean"/> + <propertyfile file="${built-clean.properties}"> + <entry key="${basedir}" value=""/> + </propertyfile> + <antcall target="-maybe-call-dep"> + <param name="call.built.properties" value="${built-clean.properties}"/> + <param location="${project.DB4o-Server}" name="call.subproject"/> + <param location="${project.DB4o-Server}/build.xml" name="call.script"/> + <param name="call.target" value="clean"/> + <param name="transfer.built-clean.properties" value="${built-clean.properties}"/> + </antcall> + </target> + <target depends="init" name="-do-clean"> + <delete dir="${build.dir}"/> + <delete dir="${dist.dir}" followsymlinks="false" includeemptydirs="true"/> + </target> + <target name="-post-clean"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,deps-clean,-do-clean,-post-clean" description="Clean build products." name="clean"/> + <target name="-check-call-dep"> + <property file="${call.built.properties}" prefix="already.built."/> + <condition property="should.call.dep"> + <not> + <isset property="already.built.${call.subproject}"/> + </not> + </condition> + </target> + <target depends="-check-call-dep" if="should.call.dep" name="-maybe-call-dep"> + <ant antfile="${call.script}" inheritall="false" target="${call.target}"> + <propertyset> + <propertyref prefix="transfer."/> + <mapper from="transfer.*" to="*" type="glob"/> + </propertyset> + </ant> + </target> +</project> diff --git a/nbproject/genfiles.properties b/nbproject/genfiles.properties new file mode 100644 index 0000000..b1f8948 --- /dev/null +++ b/nbproject/genfiles.properties @@ -0,0 +1,8 @@ +build.xml.data.CRC32=c7637cc6 +build.xml.script.CRC32=809b2dff [email protected] +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=c7637cc6 +nbproject/build-impl.xml.script.CRC32=040939fe +nbproject/[email protected] diff --git a/nbproject/private/.svn/entries b/nbproject/private/.svn/entries new file mode 100644 index 0000000..4cc8fb7 --- /dev/null +++ b/nbproject/private/.svn/entries @@ -0,0 +1,130 @@ +10 + +dir +19 +svn://localhost/spr1ngsvn/TheEye/Eye/nbproject/private +svn://localhost/spr1ngsvn/TheEye + + + +2010-06-28T07:29:35.843368Z +10 +spr1ng + + + + + + + + + + + + + + +8763ed6d-9318-4032-b958-c511fcb819a9 + +config.properties +file + + + + +2010-06-28T07:30:12.643069Z +d41d8cd98f00b204e9800998ecf8427e +2010-06-28T07:29:35.843368Z +10 +spr1ng + + + + + + + + + + + + + + + + + + + + + +0 + +private.properties +file + + + + +2010-06-28T07:30:12.643069Z +4553f6161b521153f5e430e30fdf12f9 +2010-06-28T07:29:35.843368Z +10 +spr1ng + + + + + + + + + + + + + + + + + + + + + +232 + +private.xml +file + + + + +2010-06-28T07:30:12.643069Z +325a3f155f66f3ce2c7df37de2bf87c6 +2010-06-28T07:29:35.843368Z +10 +spr1ng + + + + + + + + + + + + + + + + + + + + + +548 + diff --git a/nbproject/private/.svn/text-base/config.properties.svn-base b/nbproject/private/.svn/text-base/config.properties.svn-base new file mode 100644 index 0000000..e69de29 diff --git a/nbproject/private/.svn/text-base/private.properties.svn-base b/nbproject/private/.svn/text-base/private.properties.svn-base new file mode 100644 index 0000000..f2866fc --- /dev/null +++ b/nbproject/private/.svn/text-base/private.properties.svn-base @@ -0,0 +1,7 @@ +compile.on.save=true +do.depend=false +do.jar=true +javac.debug=true +javadoc.preview=true +jaxbwiz.endorsed.dirs=/home/spr1ng/apps/netbeans-6.8/ide12/modules/ext/jaxb/api +user.properties.file=/home/spr1ng/.netbeans/6.8/build.properties diff --git a/nbproject/private/.svn/text-base/private.xml.svn-base b/nbproject/private/.svn/text-base/private.xml.svn-base new file mode 100644 index 0000000..5378e74 --- /dev/null +++ b/nbproject/private/.svn/text-base/private.xml.svn-base @@ -0,0 +1,9 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project-private xmlns="http://www.netbeans.org/ns/project-private/1"> + <editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/1"/> + <open-files xmlns="http://www.netbeans.org/ns/projectui-open-files/1"> + <file>file:/home/spr1ng/NetBeansProjects/Eye/src/eye/Eye.java</file> + <file>file:/home/spr1ng/NetBeansProjects/Eye/src/eye/ImageFactory.java</file> + <file>file:/home/spr1ng/NetBeansProjects/Eye/src/eye/IIException.java</file> + </open-files> +</project-private> diff --git a/nbproject/private/config.properties b/nbproject/private/config.properties new file mode 100644 index 0000000..e69de29 diff --git a/nbproject/private/private.properties b/nbproject/private/private.properties new file mode 100644 index 0000000..f2866fc --- /dev/null +++ b/nbproject/private/private.properties @@ -0,0 +1,7 @@ +compile.on.save=true +do.depend=false +do.jar=true +javac.debug=true +javadoc.preview=true +jaxbwiz.endorsed.dirs=/home/spr1ng/apps/netbeans-6.8/ide12/modules/ext/jaxb/api +user.properties.file=/home/spr1ng/.netbeans/6.8/build.properties diff --git a/nbproject/private/private.xml b/nbproject/private/private.xml new file mode 100644 index 0000000..c1f155a --- /dev/null +++ b/nbproject/private/private.xml @@ -0,0 +1,4 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project-private xmlns="http://www.netbeans.org/ns/project-private/1"> + <editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/1"/> +</project-private> diff --git a/nbproject/project.properties b/nbproject/project.properties new file mode 100644 index 0000000..2b08b75 --- /dev/null +++ b/nbproject/project.properties @@ -0,0 +1,73 @@ +application.title=eye +application.vendor=Admin +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +build.generated.sources.dir=${build.dir}/generated-sources +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +# Uncomment to specify the preferred debugger connection transport: +#debug.transport=dt_socket +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/eye.jar +dist.javadoc.dir=${dist.dir}/javadoc +endorsed.classpath= +excludes= +file.reference.db4o-7.12.145.14409-all-java5.jar=../DB4o-Server/libs/db4o-7.12.145.14409-all-java5.jar +file.reference.log4j-1.2.15.jar=libs\\log4j-1.2.15.jar +includes=** +jar.compress=false +javac.classpath=\ + ${reference.DB4o-Server.jar}:\ + ${file.reference.log4j-1.2.15.jar}:\ + ${file.reference.db4o-7.12.145.14409-all-java5.jar} +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.source=1.5 +javac.target=1.5 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir}:\ + ${libs.junit.classpath}:\ + ${libs.junit_4.classpath} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding=${source.encoding} +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +jaxbwiz.endorsed.dirs="${netbeans.home}/../ide12/modules/ext/jaxb/api" +main.class=eye.Eye +manifest.file=manifest.mf +meta.inf.dir=${src.dir}/META-INF +platform.active=default_platform +project.DB4o-Server=../DB4o-Server +reference.DB4o-Server.jar=${project.DB4o-Server}/dist/DB4o-Server.jar +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value +# or test-sys-prop.name=value to set system properties for unit tests): +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +source.encoding=UTF-8 +src.dir=src +test.src.dir=test diff --git a/nbproject/project.xml b/nbproject/project.xml new file mode 100644 index 0000000..24b7095 --- /dev/null +++ b/nbproject/project.xml @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://www.netbeans.org/ns/project/1"> + <type>org.netbeans.modules.java.j2seproject</type> + <configuration> + <data xmlns="http://www.netbeans.org/ns/j2se-project/3"> + <name>eye</name> + <source-roots> + <root id="src.dir"/> + </source-roots> + <test-roots> + <root id="test.src.dir"/> + </test-roots> + </data> + <references xmlns="http://www.netbeans.org/ns/ant-project-references/1"> + <reference> + <foreign-project>DB4o-Server</foreign-project> + <artifact-type>jar</artifact-type> + <script>build.xml</script> + <target>jar</target> + <clean-target>clean</clean-target> + <id>jar</id> + </reference> + </references> + </configuration> +</project> diff --git a/src/.svn/entries b/src/.svn/entries new file mode 100644 index 0000000..e1872ca --- /dev/null +++ b/src/.svn/entries @@ -0,0 +1,65 @@ +10 + +dir +19 +svn://localhost/spr1ngsvn/TheEye/Eye/src +svn://localhost/spr1ngsvn/TheEye + + + +2010-06-30T03:16:43.109433Z +19 +stream + + + + + + + + + + + + + + +8763ed6d-9318-4032-b958-c511fcb819a9 + +eye +dir + +log4j.xml +file + + + +delete +2010-06-28T07:30:12.679068Z +7d0ca4dc1fd50bbf9008892c09c2ef8e +2010-06-28T07:29:35.843368Z +10 +spr1ng + + + + + + + + + + + + + + + + + + + + + +604 + diff --git a/src/.svn/text-base/log4j.xml.svn-base b/src/.svn/text-base/log4j.xml.svn-base new file mode 100644 index 0000000..9a584ff --- /dev/null +++ b/src/.svn/text-base/log4j.xml.svn-base @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> + + <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> + + <appender name="console" class="org.apache.log4j.ConsoleAppender"> + <param name="Target" value="System.out"/> + <layout class="org.apache.log4j.PatternLayout"> + <param name="ConversionPattern" value="%p %c: %m%n"/> + </layout> + </appender> + <!--Корневой logger--> + <root> + <priority value ="debug" /> + <appender-ref ref="console" /> + </root> + + </log4j:configuration> \ No newline at end of file diff --git a/src/eye/.svn/entries b/src/eye/.svn/entries new file mode 100644 index 0000000..9c2433b --- /dev/null +++ b/src/eye/.svn/entries @@ -0,0 +1,173 @@ +10 + +dir +19 +svn://localhost/spr1ngsvn/TheEye/Eye/src/eye +svn://localhost/spr1ngsvn/TheEye + + + +2010-06-30T03:16:43.109433Z +19 +stream + + + + + + + + + + + + + + +8763ed6d-9318-4032-b958-c511fcb819a9 + +IIException.java +file +24 + + + +2010-06-30T07:43:46.023066Z +f5fb86a8cd4dad4e8dd55a82614830b8 +2010-06-30T07:43:45.867637Z +24 +spr1ng +has-props + + + + + + + + + + + + + + + + + + + + +553 + +Eye.java +file +28 + + + +2010-07-01T05:35:24.774572Z +c337703e0f3200faa10c27a65f47a6e1 +2010-07-01T05:35:24.601857Z +28 +spr1ng +has-props + + + + + + + + + + + + + + + + + + + + +10412 + +models +dir + +config +dir + +DBManagerEyeImpl.java +file +28 + + + +2010-07-01T05:35:24.774572Z +e827050bac515a771df6d037129c208d +2010-07-01T05:35:24.601857Z +28 +spr1ng +has-props + + + + + + + + + + + + + + + + + + + + +3525 + +net +dir + +ImageFactory.java +file +28 + + + +2010-07-01T05:35:24.810571Z +3d1340fc8696be742bb67f6dc874a7e2 +2010-07-01T05:35:24.601857Z +28 +spr1ng +has-props + + + + + + + + + + + + + + + + + + + + +4824 + diff --git a/src/eye/.svn/prop-base/DBManagerEyeImpl.java.svn-base b/src/eye/.svn/prop-base/DBManagerEyeImpl.java.svn-base new file mode 100644 index 0000000..92c8ad7 --- /dev/null +++ b/src/eye/.svn/prop-base/DBManagerEyeImpl.java.svn-base @@ -0,0 +1,5 @@ +K 12 +svn:keywords +V 2 +Id +END diff --git a/src/eye/.svn/prop-base/Eye.java.svn-base b/src/eye/.svn/prop-base/Eye.java.svn-base new file mode 100644 index 0000000..92c8ad7 --- /dev/null +++ b/src/eye/.svn/prop-base/Eye.java.svn-base @@ -0,0 +1,5 @@ +K 12 +svn:keywords +V 2 +Id +END diff --git a/src/eye/.svn/prop-base/IIException.java.svn-base b/src/eye/.svn/prop-base/IIException.java.svn-base new file mode 100644 index 0000000..92c8ad7 --- /dev/null +++ b/src/eye/.svn/prop-base/IIException.java.svn-base @@ -0,0 +1,5 @@ +K 12 +svn:keywords +V 2 +Id +END diff --git a/src/eye/.svn/prop-base/ImageFactory.java.svn-base b/src/eye/.svn/prop-base/ImageFactory.java.svn-base new file mode 100644 index 0000000..92c8ad7 --- /dev/null +++ b/src/eye/.svn/prop-base/ImageFactory.java.svn-base @@ -0,0 +1,5 @@ +K 12 +svn:keywords +V 2 +Id +END diff --git a/src/eye/.svn/text-base/DBManagerEyeImpl.java.svn-base b/src/eye/.svn/text-base/DBManagerEyeImpl.java.svn-base new file mode 100644 index 0000000..520063e --- /dev/null +++ b/src/eye/.svn/text-base/DBManagerEyeImpl.java.svn-base @@ -0,0 +1,113 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package eye; + +import com.db4o.ObjectContainer; +import com.db4o.ObjectSet; +import com.db4o.cs.Db4oClientServer; +import db4oserver.AbstractDBManager; +import db4oserver.ConfigLoader; +import eye.models.Image; +import eye.models.Place; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +/** + * + * @author spr1ng + * @version $Id$ + */ +public class DBManagerEyeImpl extends AbstractDBManager{ + + private static ConfigLoader conf = ConfigLoader.getInstance(); + + public ObjectContainer getContainer() { + return Db4oClientServer.openClient(Db4oClientServer + .newClientConfiguration(), conf.getHost(), conf.getPort(), conf.getUser(), conf.getPass()); + } + + public void watchDb() { + ObjectContainer db = getContainer(); + try { + watchDb(db); + } finally { + db.close(); + } + } + + public void watchDb(ObjectContainer db) { + ObjectSet objects = db.query().execute(); + + int places = 0, images = 0; + for (Object object : objects) { + if (object instanceof Place) { + places++; + Place p = (Place) object; + LOG.info("Place url: " + p.getUrl()); + if (p.getDate() != null) { + LOG.info("Place data: " + p.getDate()); + } + } + } + LOG.info("-------> Total places: " + places); + for (Object object : objects) { + if (object instanceof Image) { + images++; + Image i = (Image) object; + LOG.info("Image: " + i.getUrl()); + if (i.getPoints() != null) { + LOG.info("!!!!!!!!!!!!!!!!!!!!!!!Points: " + i.getPoints()); + } + } + } + LOG.info("-------> Total images: " + images); + + LOG.info("Total objects: " + objects.size()); + } + + /** + * Сохраняет все объекты списка в базу. Возвращает количество новых + * сохраненных объектов + * @param objects + */ + public int store(List objects) { + if (objects == null) { + LOG.error("A try to store a null list of objects"); + return 0; + } + ObjectContainer db = getContainer(); + int qty = 0; + try { + for (Object o : objects) { + if (o != null) { + //Если такого объекта еще нет в базе + if (!isItemStored(o)) { + db.store(o); + qty++; + } //else LOG.error("A try to store a duplicate object"); //DELME: + } else LOG.error("A try to store a null object"); + } + } finally { db.close(); } + + return qty; + } + + /** Сохраняет место поиска глаза */ + public void storePlace(String firstPlace) { + //Инициализируем первое место поиска + try { + new URL(firstPlace); + } catch (MalformedURLException ex) { + LOG.error("Can't reach target: " + firstPlace, ex); + } + List<Place> places = new ArrayList<Place>(1); + places.add(new Place(firstPlace)); + store(places); + } + +} diff --git a/src/eye/.svn/text-base/Eye.java.svn-base b/src/eye/.svn/text-base/Eye.java.svn-base new file mode 100644 index 0000000..46370a2 --- /dev/null +++ b/src/eye/.svn/text-base/Eye.java.svn-base @@ -0,0 +1,307 @@ +package eye; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Date; +import java.util.Scanner; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.net.URL; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.util.HashSet; +import java.util.Set; +import org.apache.log4j.Logger; +import com.db4o.ObjectContainer; +import com.db4o.ObjectSet; +import com.db4o.query.Query; + +import eye.models.Image; +import eye.models.Place; +import static eye.net.InetUtils.*; + +/** + * The Eye - yet another crawler ;) + * @author gpdribbler, spr1ng + * @version $Id$ + */ +public class Eye { + private static final Logger LOG = Logger.getLogger(Eye.class); + private static DBManagerEyeImpl dbm = new DBManagerEyeImpl(); + + public Eye() { +// setProxy("cmdeviant", 3128, "alexey", "ahGueb1e"); + } + + private static final int PORT = 4488; + private static final String USER = "db4o"; + private static final String PASS = "db4o"; + + + + /*public static ObjectContainer getConnection() { + return Db4oClientServer.openClient(Db4oClientServer + .newClientConfiguration(), "localhost", PORT, USER, PASS); + }*/ + + public List<Place> grubPlaces(String pageSource) { + List<String> regExps = new ArrayList<String>(9); + regExps.add(".+js$"); + regExps.add(".+xml$"); + regExps.add(".+swf$"); + regExps.add(".+dtd$"); + regExps.add(".+jpg$"); + regExps.add(".+gif$"); + regExps.add(".+bmp$"); + regExps.add(".+png$"); + //TODO: добавить подждержку ico + regExps.add(".+ico$"); + + List<Place> places = new ArrayList<Place>(); + Set<URL> placeUrls = grubURLs(regExps, true); + for (URL placeUrl : placeUrls) { + places.add(new Place(placeUrl.toString()));//PENDING + } + + return places; + } + + public List<Image> grubImages(String pageSource) { + List<String> regExps = new ArrayList<String>(4); + regExps.add(".+jpg$"); + regExps.add(".+gif$"); + regExps.add(".+bmp$"); + regExps.add(".+png$"); + + List<Image> images = new ArrayList<Image>(); + Set<URL> imageUrls = grubURLs(regExps); + for (URL imageUrl : imageUrls) { + try { + images.add(new Image(imageUrl.toString())); + } catch (Exception ex) { + LOG.error("Can't produce image from url " + imageUrl); + } + } + + return images; + } + + /** + * + * @param pageSource + * @param regExps + * @param isExcludeMode если true - url-ки, соответствующие регуляркам + * не будут включены в список, иначе - будут включены только те, которые + * соответствуют регуляркам + * @return + */ + public Set<URL> grubURLs(List<String> regExps, boolean isExcludeMode) { + Set<URL> urls = new HashSet<URL>(); + String urlRegExp = "https?://[-_=+/,.?!&%~:|;#\\w\\d]+";//PENDING + + String[] words = pageSource.split("\\s"); + for (String word : words) { + word = word.replaceFirst(".*?http", "http"); + if (!word.startsWith("http")){ + word = word.replaceFirst(".*?href=\"/", "http://" + domain + "/"); + word = word.replaceFirst(".*?href='/", "http://" + domain + "/"); + word = word.replaceFirst(".*?src=\"/", "http://" + domain + "/"); + word = word.replaceFirst(".*?src='/", "http://" + domain + "/"); + } + String url = findRegexp(word, urlRegExp); + if (url != null) { + try { + url = url.replaceFirst("/$", "");//убираем последний слэшик, чтобы избежать дублирования ссылок + urls.add(new URL(url)); + } catch (MalformedURLException ex) { + LOG.error("Incorrect url: " + url, ex); + } + } + } + //Если вызван без регулярок - возвращаем все url + if (regExps == null) { + return urls; + } + for (Iterator<URL> url = urls.iterator(); url.hasNext();) { + String res = findRegexp(url.next().toString(), regExps); + if (isExcludeMode) { + if (res != null) { + url.remove(); + } + } else { + if (res == null) { + url.remove(); + } + } + } + return urls; + } + + /** + * Возвращает список всех url, найденных в исходнике страницы + * @param pageSource + * @return + */ + public Set<URL> grubURLs() { + return grubURLs(null, false); + } + + /** + * Возвращает список url, найденных в исходнике страницы, соответсвующим регуляркам + * @param pageSource + * @return + */ + public Set<URL> grubURLs(List<String> regExps) { + return grubURLs(regExps, false); + } + + private static String pageSource = ""; + private static String domain = ""; + public void run() { + ObjectContainer db = dbm.getContainer(); + try { + + Runnable imagesGrubbing = new Runnable() { + public void run() { + List<Image> images = grubImages(pageSource); + if (images.size() > 0) { + long t1 = System.currentTimeMillis(); + int savedQty = dbm.store(images); + long t2 = System.currentTimeMillis() - t1; + if (savedQty > 0) + LOG.info("---------> Storing new images [" + savedQty + "] done. --> " + t2 + " ms"); + } + } + }; + + Runnable placesGrubbing = new Runnable() { + public void run() { + List<Place> places = grubPlaces(pageSource); + if (places.size() > 0) { + long t1 = System.currentTimeMillis(); + int savedQty = dbm.store(places); + long t2 = System.currentTimeMillis() - t1; + if (savedQty > 0) + LOG.info("---------> Storing new places [" + savedQty + "] done. --> " + t2 + " ms"); + } + } + }; + + Query query = db.query(); + query.constrain(Place.class); + query.descend("date").orderAscending();//те, что без даты сортируются наверх + + int placeIdx = 0; + ObjectSet<Place> places = query.execute(); + LOG.info("Places in db: " + places.size()); + + for (Place p : places) { + try { + placeIdx++; + LOG.info("[" + placeIdx + "/" + places.size() + "] Seeking in " + p.getUrl()); + //Данные для grubURL(); + URL u = new URL(p.getUrl()); + pageSource = getPageSource(u); + domain = u.getHost(); + + ThreadGroup tg = new ThreadGroup("sources"); + new Thread(tg, imagesGrubbing).start(); + new Thread(tg, placesGrubbing).start(); + + //Ждем завершения потоков.. + while(tg.activeCount() > 0) Thread.sleep(10); + + p.setDate(new Date()); + db.store(p); + } catch (Exception ex) { + db.delete(p); + LOG.error(ex); + } finally { + db.commit(); + } + } + } finally { + db.close(); + } + + }//seek + + + + public static void main(String[] args) throws InterruptedException, MalformedURLException { + if (!hasInetConnection()) { + LOG.error("Inet is unreachable! =("); + System.exit(1); + } + + Eye eye = new Eye(); + dbm.storePlace("http://ya.ru"); +// eye.watchDb(); + eye.run(); + /*while (true) { + eye.run(); + Thread.sleep(1000); + }*/ + /*URL u = new URL("http://ya.ru"); + pageSource = eye.getPageSource(u); + domain = u.getHost(); + Set<URL> urls = eye.grubURLs(); + for (URL url : urls) { + System.out.println(url); + } + System.out.println("size: " + urls.size());*/ + } + + /** + * Находит фрагмент строки из source, соответстующий любой регулярке из regs + * @param source + * @param regs + * @return + */ + private String findRegexp(String source, List<String> regs) { + for (String reg : regs) { + Pattern pattern = Pattern.compile(reg); + Matcher matcher = pattern.matcher(source.toLowerCase()); + if (matcher.find()) { + return matcher.group(); + } + } + return null; + } + + /** + * Находит фрагмент строки из source, соответстующий регулярке из reg + * @param source + * @param reg + * @return + */ + private String findRegexp(String source, String reg) { + List<String> regs = new ArrayList<String>(1); + regs.add(reg); + return findRegexp(source, regs); + } + + private String getPageSource(URL url) { + StringBuilder response = new StringBuilder(); + + HttpURLConnection con; + try { + con = (HttpURLConnection) url.openConnection(); +// con.setRequestProperty("Accept-Charset", "cp1251"); + con.connect(); + Scanner scanner = new Scanner(con.getInputStream()); + while (scanner.hasNext()) { + response.append(scanner.nextLine()); + } + + con.disconnect(); + } catch (Exception ex) { + LOG.error("The place is unreachable: " + url); + return ""; + } + + return response.toString(); + } + +} diff --git a/src/eye/.svn/text-base/IIException.java.svn-base b/src/eye/.svn/text-base/IIException.java.svn-base new file mode 100644 index 0000000..2f8e2eb --- /dev/null +++ b/src/eye/.svn/text-base/IIException.java.svn-base @@ -0,0 +1,29 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package eye; + +import java.io.IOException; + +/** + * IncorrectImageException + * @author spr1ng + * @version $Id$ + */ +public class IIException extends IOException { + + public IIException(String message) { + super(message); + } + + public IIException(Throwable cause) { + super(cause); + } + + public IIException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/src/eye/.svn/text-base/ImageFactory.java.svn-base b/src/eye/.svn/text-base/ImageFactory.java.svn-base new file mode 100644 index 0000000..610cd6c --- /dev/null +++ b/src/eye/.svn/text-base/ImageFactory.java.svn-base @@ -0,0 +1,160 @@ +package eye; + +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; +import java.awt.image.BufferedImageOp; +import java.awt.image.ConvolveOp; +import java.awt.image.Kernel; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import javax.imageio.ImageIO; +import eye.models.Point; +import eye.models.Image; +import static eye.net.InetUtils.*; + +/** + * + * @author gpdribbler, spr1ng + * @version $Id$ + */ +public class ImageFactory { + + private final static int DEPTH = 25; + //TODO: сделать дисперсию долевой от размеров картинки + private final static int DISPERSION = 20; + private final static int MIN_WIDTH = 128; + private final static int MIN_HEIGHT = 128; + + private BufferedImage bimg; + private ArrayList<Point> points; + + public void load(File file) throws IOException { + bimg = ImageIO.read(file); + } + + public void load(URL url) throws IOException { + //Зададим-ка мы проверочку на таймаут + if (isReachable(url.toString(), 3000)) + bimg = ImageIO.read(url); + else throw new IIException("Connection timeout"); + } + + /** + * Создает BufferedImage из потока + * @param in входящий поток + * @throws IOException + */ + public void load(InputStream in) throws IOException { + bimg = ImageIO.read(in); + } + + public void saveToFile(String fileName) throws IOException { + ImageIO.write(bimg, getExtension(fileName), new File(fileName)); + } + + /** + * Saves to output stream + * @param imgExtension + * @param out + * @throws IOException + */ + public void saveToOutputStream(String imgExtension, OutputStream out) throws IOException { + ImageIO.write(bimg, imgExtension, out); + } + + /** + * Рисует области вокруг точек белым цветом + * @param points + */ + public void draw(List<Point> points) { + draw(points, Color.WHITE); + } + + /** + * Рисует области вокруг точек выбранным цветом + * @param points + * @param color + */ + public void draw(List<Point> points, Color color){ + int d = 20; + Graphics2D graphics = bimg.createGraphics(); + for (Iterator<Point> it = points.iterator(); it.hasNext();) { + Point point = it.next(); + graphics.setColor(color); + graphics.drawOval(point.getX()-(d/2), point.getY()-(d/2), d, d); + } + } + + public List<Point> seekPoints(InputStream in) throws IOException{ + load(in); + return seekPoints(); + } + + public List<Point> seekPoints(){ + try { + Kernel kernel = new Kernel(3, 3, new float[]{1f / 9f, 1f / 9f, 1f / 9f, + 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f}); + BufferedImageOp op = new ConvolveOp(kernel); + bimg = op.filter(bimg, null); + } catch (Exception e) { + } + + points = new ArrayList<Point>(); + + //TODO: проверить значение декремента + int w = bimg.getWidth()-4; + int h = bimg.getHeight()-4; + for(int i = 2; i < w; i++) + for(int j = 2; j < h; j++) { + Point point = new Point(i, j, bimg); + if(point.isBorder(DEPTH)) points.add(point); + }//for + + //TODO: увеличить эффективность за счет просмотра только ближайших точек + for(int i = 0; i < points.size(); i++) + for(int j = i+1; j < points.size(); j++) + if(points.get(i).compareTo(points.get(j)) < DISPERSION) { + points.remove(j); + j--; + } + + return points; + + }//seekPoints() + + private boolean hasValidSize() { + if( (bimg.getWidth() >= MIN_WIDTH) && (bimg.getHeight() >= MIN_HEIGHT) ) { + return true; + } else { + return false; + } + }//checkMeasurement + + public void produceMetaImage(Image image) throws IOException { + load(new URL(image.getUrl())); + + if(hasValidSize()) { + image.setPoints(seekPoints()); + System.out.println(image); + } else { + throw new IIException("Invalid image size."); + } + } + + /** + * Gets file extension + * @param fileName + * @return + */ + public static String getExtension(String fileName){ + return fileName.replaceFirst(".*\\.", ""); + } + +} diff --git a/src/eye/DBManagerEyeImpl.java b/src/eye/DBManagerEyeImpl.java new file mode 100644 index 0000000..2bcf93f --- /dev/null +++ b/src/eye/DBManagerEyeImpl.java @@ -0,0 +1,115 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package eye; + +import com.db4o.ObjectContainer; +import com.db4o.ObjectSet; +import com.db4o.cs.Db4oClientServer; +import db4oserver.AbstractDBManager; +import db4oserver.ConfigLoader; +import eye.models.Image; +import eye.models.Place; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; +import org.apache.log4j.Logger; + +/** + * + * @author spr1ng + * @version $Id: DBManagerEyeImpl.java 28 2010-07-01 05:35:24Z spr1ng $ + */ +public class DBManagerEyeImpl extends AbstractDBManager{ + + private static ConfigLoader conf = ConfigLoader.getInstance(); + public static final Logger LOG = Logger.getLogger(DBManagerEyeImpl.class); + + public ObjectContainer getContainer() { + return Db4oClientServer.openClient(Db4oClientServer + .newClientConfiguration(), conf.getHost(), conf.getPort(), conf.getUser(), conf.getPass()); + } + + public void watchDb() { + ObjectContainer db = getContainer(); + try { + watchDb(db); + } finally { + db.close(); + } + } + + public void watchDb(ObjectContainer db) { + ObjectSet objects = db.query().execute(); + + int places = 0, images = 0; + for (Object object : objects) { + if (object instanceof Place) { + places++; + Place p = (Place) object; + LOG.info("Place url: " + p.getUrl()); + if (p.getDate() != null) { + LOG.info("Place data: " + p.getDate()); + } + } + } + LOG.info("-------> Total places: " + places); + for (Object object : objects) { + if (object instanceof Image) { + images++; + Image i = (Image) object; + LOG.info("Image: " + i.getUrl()); + if (i.getPoints() != null) { + LOG.info("!!!!!!!!!!!!!!!!!!!!!!!Points: " + i.getPoints()); + } + } + } + LOG.info("-------> Total images: " + images); + + LOG.info("Total objects: " + objects.size()); + } + + /** + * Сохраняет все объекты списка в базу. Возвращает количество новых + * сохраненных объектов + * @param objects + */ + public int store(List objects) { + if (objects == null) { + LOG.error("A try to store a null list of objects"); + return 0; + } + ObjectContainer db = getContainer(); + int qty = 0; + try { + for (Object o : objects) { + if (o != null) { + //Если такого объекта еще нет в базе + if (!isItemStored(o)) { + db.store(o); + qty++; + } //else LOG.error("A try to store a duplicate object"); //DELME: + } else LOG.error("A try to store a null object"); + } + } finally { db.close(); } + + return qty; + } + + /** Сохраняет место поиска глаза */ + public void storePlace(String firstPlace) { + //Инициализируем первое место поиска + try { + new URL(firstPlace); + } catch (MalformedURLException ex) { + LOG.error("Can't reach target: " + firstPlace, ex); + } + List<Place> places = new ArrayList<Place>(1); + places.add(new Place(firstPlace)); + store(places); + } + +} diff --git a/src/eye/Eye.java b/src/eye/Eye.java new file mode 100644 index 0000000..4c1870a --- /dev/null +++ b/src/eye/Eye.java @@ -0,0 +1,296 @@ +package eye; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Date; +import java.util.Scanner; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.net.URL; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.util.HashSet; +import java.util.Set; +import org.apache.log4j.Logger; +import com.db4o.ObjectContainer; +import com.db4o.ObjectSet; +import com.db4o.query.Query; + +import eye.models.Image; +import eye.models.Place; +import static eye.net.InetUtils.*; + +/** + * The Eye - yet another crawler ;) + * @author gpdribbler, spr1ng + * @version $Id: Eye.java 28 2010-07-01 05:35:24Z spr1ng $ + */ +public class Eye { + private static final Logger LOG = Logger.getLogger(Eye.class); + private static DBManagerEyeImpl dbm = new DBManagerEyeImpl(); + + public Eye() { +// setProxy("cmdeviant", 3128, "alexey", "ahGueb1e"); + } + + public List<Place> grubPlaces(String pageSource) { + List<String> regExps = new ArrayList<String>(9); + regExps.add(".+js$"); + regExps.add(".+xml$"); + regExps.add(".+swf$"); + regExps.add(".+dtd$"); + regExps.add(".+jpg$"); + regExps.add(".+gif$"); + regExps.add(".+bmp$"); + regExps.add(".+png$"); + //TODO: добавить подждержку ico + regExps.add(".+ico$"); + + List<Place> places = new ArrayList<Place>(); + Set<URL> placeUrls = grubURLs(regExps, true); + for (URL placeUrl : placeUrls) { + places.add(new Place(placeUrl.toString()));//PENDING + } + + return places; + } + + public List<Image> grubImages(String pageSource) { + List<String> regExps = new ArrayList<String>(4); + regExps.add(".+jpg$"); + regExps.add(".+gif$"); + regExps.add(".+bmp$"); + regExps.add(".+png$"); + + List<Image> images = new ArrayList<Image>(); + Set<URL> imageUrls = grubURLs(regExps); + for (URL imageUrl : imageUrls) { + try { + images.add(new Image(imageUrl.toString())); + } catch (Exception ex) { + LOG.error("Can't produce image from url " + imageUrl); + } + } + + return images; + } + + /** + * + * @param pageSource + * @param regExps + * @param isExcludeMode если true - url-ки, соответствующие регуляркам + * не будут включены в список, иначе - будут включены только те, которые + * соответствуют регуляркам + * @return + */ + public Set<URL> grubURLs(List<String> regExps, boolean isExcludeMode) { + Set<URL> urls = new HashSet<URL>(); + String urlRegExp = "https?://[-_=+/,.?!&%~:|;#\\w\\d]+";//PENDING + + String[] words = pageSource.split("\\s"); + for (String word : words) { + word = word.replaceFirst(".*?http", "http"); + if (!word.startsWith("http")){ + word = word.replaceFirst(".*?href=\"/", "http://" + domain + "/"); + word = word.replaceFirst(".*?href='/", "http://" + domain + "/"); + word = word.replaceFirst(".*?src=\"/", "http://" + domain + "/"); + word = word.replaceFirst(".*?src='/", "http://" + domain + "/"); + } + String url = findRegexp(word, urlRegExp); + if (url != null) { + try { + url = url.replaceFirst("/$", "");//убираем последний слэшик, чтобы избежать дублирования ссылок + urls.add(new URL(url)); + } catch (MalformedURLException ex) { + LOG.error("Incorrect url: " + url, ex); + } + } + } + //Если вызван без регулярок - возвращаем все url + if (regExps == null) { + return urls; + } + for (Iterator<URL> url = urls.iterator(); url.hasNext();) { + String res = findRegexp(url.next().toString(), regExps); + if (isExcludeMode) { + if (res != null) { + url.remove(); + } + } else { + if (res == null) { + url.remove(); + } + } + } + return urls; + } + + /** + * Возвращает список всех url, найденных в исходнике страницы + * @param pageSource + * @return + */ + public Set<URL> grubURLs() { + return grubURLs(null, false); + } + + /** + * Возвращает список url, найденных в исходнике страницы, соответсвующим регуляркам + * @param pageSource + * @return + */ + public Set<URL> grubURLs(List<String> regExps) { + return grubURLs(regExps, false); + } + + private static String pageSource = ""; + private static String domain = ""; + public void run() { + ObjectContainer db = dbm.getContainer(); + try { + + Runnable imagesGrubbing = new Runnable() { + public void run() { + List<Image> images = grubImages(pageSource); + if (images.size() > 0) { + long t1 = System.currentTimeMillis(); + int savedQty = dbm.store(images); + long t2 = System.currentTimeMillis() - t1; + if (savedQty > 0) + LOG.info("---------> Storing new images [" + savedQty + "] done. --> " + t2 + " ms"); + } + } + }; + + Runnable placesGrubbing = new Runnable() { + public void run() { + List<Place> places = grubPlaces(pageSource); + if (places.size() > 0) { + long t1 = System.currentTimeMillis(); + int savedQty = dbm.store(places); + long t2 = System.currentTimeMillis() - t1; + if (savedQty > 0) + LOG.info("---------> Storing new places [" + savedQty + "] done. --> " + t2 + " ms"); + } + } + }; + + Query query = db.query(); + query.constrain(Place.class); + query.descend("date").orderAscending();//те, что без даты сортируются наверх + + int placeIdx = 0; + ObjectSet<Place> places = query.execute(); + LOG.info("Places in db: " + places.size()); + + for (Place p : places) { + try { + placeIdx++; + LOG.info("[" + placeIdx + "/" + places.size() + "] Seeking in " + p.getUrl()); + //Данные для grubURL(); + URL u = new URL(p.getUrl()); + pageSource = getPageSource(u); + domain = u.getHost(); + + ThreadGroup tg = new ThreadGroup("sources"); + new Thread(tg, imagesGrubbing).start(); + new Thread(tg, placesGrubbing).start(); + + //Ждем завершения потоков.. + while(tg.activeCount() > 0) Thread.sleep(10); + + p.setDate(new Date()); + db.store(p); + } catch (Exception ex) { + db.delete(p); + LOG.error(ex); + } finally { + db.commit(); + } + } + } finally { + db.close(); + } + + }//seek + + + + public static void main(String[] args) throws InterruptedException, MalformedURLException { + if (!hasInetConnection()) { + LOG.error("Inet is unreachable! =("); + System.exit(1); + } + + Eye eye = new Eye(); + dbm.storePlace("http://ya.ru"); +// eye.watchDb(); + eye.run(); + /*while (true) { + eye.run(); + Thread.sleep(1000); + }*/ + /*URL u = new URL("http://ya.ru"); + pageSource = eye.getPageSource(u); + domain = u.getHost(); + Set<URL> urls = eye.grubURLs(); + for (URL url : urls) { + System.out.println(url); + } + System.out.println("size: " + urls.size());*/ + } + + /** + * Находит фрагмент строки из source, соответстующий любой регулярке из regs + * @param source + * @param regs + * @return + */ + private String findRegexp(String source, List<String> regs) { + for (String reg : regs) { + Pattern pattern = Pattern.compile(reg); + Matcher matcher = pattern.matcher(source.toLowerCase()); + if (matcher.find()) { + return matcher.group(); + } + } + return null; + } + + /** + * Находит фрагмент строки из source, соответстующий регулярке из reg + * @param source + * @param reg + * @return + */ + private String findRegexp(String source, String reg) { + List<String> regs = new ArrayList<String>(1); + regs.add(reg); + return findRegexp(source, regs); + } + + private String getPageSource(URL url) { + StringBuilder response = new StringBuilder(); + + HttpURLConnection con; + try { + con = (HttpURLConnection) url.openConnection(); +// con.setRequestProperty("Accept-Charset", "cp1251"); + con.connect(); + Scanner scanner = new Scanner(con.getInputStream()); + while (scanner.hasNext()) { + response.append(scanner.nextLine()); + } + + con.disconnect(); + } catch (Exception ex) { + LOG.error("The place is unreachable: " + url); + return ""; + } + + return response.toString(); + } + +} diff --git a/src/eye/IIException.java b/src/eye/IIException.java new file mode 100644 index 0000000..3682a91 --- /dev/null +++ b/src/eye/IIException.java @@ -0,0 +1,29 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package eye; + +import java.io.IOException; + +/** + * IncorrectImageException + * @author spr1ng + * @version $Id: IIException.java 24 2010-06-30 07:43:45Z spr1ng $ + */ +public class IIException extends IOException { + + public IIException(String message) { + super(message); + } + + public IIException(Throwable cause) { + super(cause); + } + + public IIException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/src/eye/ImageFactory.java b/src/eye/ImageFactory.java new file mode 100644 index 0000000..83d2ac9 --- /dev/null +++ b/src/eye/ImageFactory.java @@ -0,0 +1,160 @@ +package eye; + +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; +import java.awt.image.BufferedImageOp; +import java.awt.image.ConvolveOp; +import java.awt.image.Kernel; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import javax.imageio.ImageIO; +import eye.models.Point; +import eye.models.Image; +import static eye.net.InetUtils.*; + +/** + * + * @author gpdribbler, spr1ng + * @version $Id: ImageFactory.java 28 2010-07-01 05:35:24Z spr1ng $ + */ +public class ImageFactory { + + private final static int DEPTH = 25; + //TODO: сделать дисперсию долевой от размеров картинки + private final static int DISPERSION = 20; + private final static int MIN_WIDTH = 128; + private final static int MIN_HEIGHT = 128; + + private BufferedImage bimg; + private ArrayList<Point> points; + + public void load(File file) throws IOException { + bimg = ImageIO.read(file); + } + + public void load(URL url) throws IOException { + //Зададим-ка мы проверочку на таймаут + if (isReachable(url.toString(), 3000)) + bimg = ImageIO.read(url); + else throw new IIException("Connection timeout"); + } + + /** + * Создает BufferedImage из потока + * @param in входящий поток + * @throws IOException + */ + public void load(InputStream in) throws IOException { + bimg = ImageIO.read(in); + } + + public void saveToFile(String fileName) throws IOException { + ImageIO.write(bimg, getExtension(fileName), new File(fileName)); + } + + /** + * Saves to output stream + * @param imgExtension + * @param out + * @throws IOException + */ + public void saveToOutputStream(String imgExtension, OutputStream out) throws IOException { + ImageIO.write(bimg, imgExtension, out); + } + + /** + * Рисует области вокруг точек белым цветом + * @param points + */ + public void draw(List<Point> points) { + draw(points, Color.WHITE); + } + + /** + * Рисует области вокруг точек выбранным цветом + * @param points + * @param color + */ + public void draw(List<Point> points, Color color){ + int d = 20; + Graphics2D graphics = bimg.createGraphics(); + for (Iterator<Point> it = points.iterator(); it.hasNext();) { + Point point = it.next(); + graphics.setColor(color); + graphics.drawOval(point.getX()-(d/2), point.getY()-(d/2), d, d); + } + } + + public List<Point> seekPoints(InputStream in) throws IOException{ + load(in); + return seekPoints(); + } + + public List<Point> seekPoints(){ + try { + Kernel kernel = new Kernel(3, 3, new float[]{1f / 9f, 1f / 9f, 1f / 9f, + 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f}); + BufferedImageOp op = new ConvolveOp(kernel); + bimg = op.filter(bimg, null); + } catch (Exception e) { + } + + points = new ArrayList<Point>(); + + //TODO: проверить значение декремента + int w = bimg.getWidth()-4; + int h = bimg.getHeight()-4; + for(int i = 2; i < w; i++) + for(int j = 2; j < h; j++) { + Point point = new Point(i, j, bimg); + if(point.isBorder(DEPTH)) points.add(point); + }//for + + //TODO: увеличить эффективность за счет просмотра только ближайших точек + for(int i = 0; i < points.size(); i++) + for(int j = i+1; j < points.size(); j++) + if(points.get(i).compareTo(points.get(j)) < DISPERSION) { + points.remove(j); + j--; + } + + return points; + + }//seekPoints() + + private boolean hasValidSize() { + if( (bimg.getWidth() >= MIN_WIDTH) && (bimg.getHeight() >= MIN_HEIGHT) ) { + return true; + } else { + return false; + } + }//checkMeasurement + + public void produceMetaImage(Image image) throws IOException { + load(new URL(image.getUrl())); + + if(hasValidSize()) { + image.setPoints(seekPoints()); + System.out.println(image); + } else { + throw new IIException("Invalid image size."); + } + } + + /** + * Gets file extension + * @param fileName + * @return + */ + public static String getExtension(String fileName){ + return fileName.replaceFirst(".*\\.", ""); + } + +} diff --git a/src/eye/config/.svn/entries b/src/eye/config/.svn/entries new file mode 100644 index 0000000..579e827 --- /dev/null +++ b/src/eye/config/.svn/entries @@ -0,0 +1,28 @@ +10 + +dir +19 +svn://localhost/spr1ngsvn/TheEye/Eye/src/eye/config +svn://localhost/spr1ngsvn/TheEye + + + +2010-06-28T07:29:35.843368Z +10 +spr1ng + + + + + + + + + + + + + + +8763ed6d-9318-4032-b958-c511fcb819a9 + diff --git a/src/eye/models/.svn/entries b/src/eye/models/.svn/entries new file mode 100644 index 0000000..b15fe29 --- /dev/null +++ b/src/eye/models/.svn/entries @@ -0,0 +1,164 @@ +10 + +dir +19 +svn://localhost/spr1ngsvn/TheEye/Eye/src/eye/models +svn://localhost/spr1ngsvn/TheEye + + + +2010-06-30T03:16:43.109433Z +19 +stream + + + + + + + + + + + + + + +8763ed6d-9318-4032-b958-c511fcb819a9 + +Image.java +file +24 + + + +2010-06-30T07:43:46.027067Z +665663343142c8b25db9fd2bffa0078a +2010-06-30T07:43:45.867637Z +24 +spr1ng +has-props + + + + + + + + + + + + + + + + + + + + +1388 + +Place.java +file +24 + + + +2010-06-30T07:43:46.027067Z +f60f503b66e1c6d23ef0187d37bc7ca9 +2010-06-30T07:43:45.867637Z +24 +spr1ng +has-props + + + + + + + + + + + + + + + + + + + + +800 + +Point.java +file +24 + + + +2010-06-30T07:43:46.027067Z +6eeba21d167396d9c9f91a2f1e7f6311 +2010-06-30T07:43:45.867637Z +24 +spr1ng +has-props + + + + + + + + + + + + + + + + + + + + +2064 + +RemoteSource.java +file +24 + + + +2010-06-30T07:43:46.031066Z +fd8ca6805676363a6121820c667a3e3c +2010-06-30T07:43:45.867637Z +24 +spr1ng +has-props + + + + + + + + + + + + + + + + + + + + +322 + diff --git a/src/eye/models/.svn/prop-base/Image.java.svn-base b/src/eye/models/.svn/prop-base/Image.java.svn-base new file mode 100644 index 0000000..92c8ad7 --- /dev/null +++ b/src/eye/models/.svn/prop-base/Image.java.svn-base @@ -0,0 +1,5 @@ +K 12 +svn:keywords +V 2 +Id +END diff --git a/src/eye/models/.svn/prop-base/Place.java.svn-base b/src/eye/models/.svn/prop-base/Place.java.svn-base new file mode 100644 index 0000000..92c8ad7 --- /dev/null +++ b/src/eye/models/.svn/prop-base/Place.java.svn-base @@ -0,0 +1,5 @@ +K 12 +svn:keywords +V 2 +Id +END diff --git a/src/eye/models/.svn/prop-base/Point.java.svn-base b/src/eye/models/.svn/prop-base/Point.java.svn-base new file mode 100644 index 0000000..92c8ad7 --- /dev/null +++ b/src/eye/models/.svn/prop-base/Point.java.svn-base @@ -0,0 +1,5 @@ +K 12 +svn:keywords +V 2 +Id +END diff --git a/src/eye/models/.svn/prop-base/RemoteSource.java.svn-base b/src/eye/models/.svn/prop-base/RemoteSource.java.svn-base new file mode 100644 index 0000000..92c8ad7 --- /dev/null +++ b/src/eye/models/.svn/prop-base/RemoteSource.java.svn-base @@ -0,0 +1,5 @@ +K 12 +svn:keywords +V 2 +Id +END diff --git a/src/eye/models/.svn/text-base/Image.java.svn-base b/src/eye/models/.svn/text-base/Image.java.svn-base new file mode 100644 index 0000000..e402c14 --- /dev/null +++ b/src/eye/models/.svn/text-base/Image.java.svn-base @@ -0,0 +1,65 @@ +package eye.models; + +import java.util.Iterator; +import java.util.List; + +/** + * + * @author gpdribbler, spr1ng, stream + * @version $Id$ + */ +public class Image implements RemoteSource{ + + private String url; + private List<Point> points; + + public Image() { + } + + public Image(String url) { + this.url = url; + } + + public Image(String url, List<Point> points) { + this.url = url; + this.points = points; + } + + public List<Point> getPoints() { + return points; + } + + public void setPoints(List<Point> points) { + this.points = points; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + @Override + public String toString() { + String result = "";//url.toString(); + result += ": " + points.size() + " points"; + return result; + } + + //TODO: реализовать + public int compareTo(Image image) { + int result = 0; + for (Iterator<Point> it = points.iterator(); it.hasNext();) + for (Iterator<Point> it1 = image.getPoints().iterator(); it.hasNext();) + result += it.next().compareTo(it1.next()); + return result; + } + + public boolean hasMetaData(){ + if (points == null) return false; + return true; + } + +} diff --git a/src/eye/models/.svn/text-base/Place.java.svn-base b/src/eye/models/.svn/text-base/Place.java.svn-base new file mode 100644 index 0000000..98d9ac7 --- /dev/null +++ b/src/eye/models/.svn/text-base/Place.java.svn-base @@ -0,0 +1,48 @@ +package eye.models; + +import java.util.Date; + +/** + * + * @author gpdribbler, spr1ng, stream + * @version $Id$ + */ +public class Place implements RemoteSource{ + + private String url; + private Date date; + + public Place() { + } + + public Place(String url, Date date) { + this.url = url; + this.date = date; + } + + public Place(String url) { + this.url = url; + } + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + @Override + public String toString() { + return url + " " + String.valueOf(date); + } + +} diff --git a/src/eye/models/.svn/text-base/Point.java.svn-base b/src/eye/models/.svn/text-base/Point.java.svn-base new file mode 100644 index 0000000..4c3c89c --- /dev/null +++ b/src/eye/models/.svn/text-base/Point.java.svn-base @@ -0,0 +1,86 @@ +package eye.models; + +import java.awt.image.BufferedImage; + +/** + * + * @author gpdribbler + * @version $Id$ + */ +public class Point { + + private int x; + private int y; + private BufferedImage image; + + public Point() { + } + + public Point(int x, int y, BufferedImage image) { + this.x = x; + this.y = y; + this.image = image; + } + + //TODO: вычислять расстояние с поправкой на рубежность точки? + public int compareTo(Point p) { + int result = (x - p.getX()) * (x - p.getX()); + result += (y - p.getY()) * (y - p.getY()); + return (int) Math.sqrt(result); + } + + public boolean isBorder(int limit) { + int diff = 0; + for(int i = -1; i <= 1; i++) + for(int j = -1; j <= 1; j++) + diff += getRGBDifference(new Point(x+i, y+j, image)); + diff /= 8; + if(diff > limit) { + return true; + } else { + return false; + } + }//isBorderPixel + + public int getRGBDifference(Point point) { + int rgb1 = image.getRGB(x, y); + int rgb2 = image.getRGB(point.getX(), point.getY()); + + int red1 = (rgb1 & 0x00ff0000) >> 16; + int green1 = (rgb1 & 0x0000ff00) >> 8; + int blue1 = (rgb1 & 0x000000ff); + + int red2 = (rgb2 & 0x00ff0000) >> 16; + int green2 = (rgb2 & 0x0000ff00) >> 8; + int blue2 = (rgb2 & 0x000000ff); + + return (int) Math.sqrt( (red1 - red2)*(red1 - red2) + (green1 - green2) + * (green1 - green2) + (blue1 - blue2) * (blue1 - blue2) ); + }//getDifference + + + public int getX() { + return x; + } + + public void setX(int x) { + this.x = x; + } + + public int getY() { + return y; + } + + public void setY(int y) { + this.y = y; + } + + public BufferedImage getImage() { + return image; + } + + public void setImage(BufferedImage image) { + this.image = image; + } + +} diff --git a/src/eye/models/.svn/text-base/RemoteSource.java.svn-base b/src/eye/models/.svn/text-base/RemoteSource.java.svn-base new file mode 100644 index 0000000..61f1e34 --- /dev/null +++ b/src/eye/models/.svn/text-base/RemoteSource.java.svn-base @@ -0,0 +1,17 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package eye.models; + +/** + * + * @author stream + * @version $Id$ + */ +public interface RemoteSource { + + public String getUrl(); + public void setUrl(String url); + +} diff --git a/src/eye/models/Image.java b/src/eye/models/Image.java new file mode 100644 index 0000000..df5f28d --- /dev/null +++ b/src/eye/models/Image.java @@ -0,0 +1,65 @@ +package eye.models; + +import java.util.Iterator; +import java.util.List; + +/** + * + * @author gpdribbler, spr1ng, stream + * @version $Id: Image.java 24 2010-06-30 07:43:45Z spr1ng $ + */ +public class Image implements RemoteSource{ + + private String url; + private List<Point> points; + + public Image() { + } + + public Image(String url) { + this.url = url; + } + + public Image(String url, List<Point> points) { + this.url = url; + this.points = points; + } + + public List<Point> getPoints() { + return points; + } + + public void setPoints(List<Point> points) { + this.points = points; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + @Override + public String toString() { + String result = "";//url.toString(); + result += ": " + points.size() + " points"; + return result; + } + + //TODO: реализовать + public int compareTo(Image image) { + int result = 0; + for (Iterator<Point> it = points.iterator(); it.hasNext();) + for (Iterator<Point> it1 = image.getPoints().iterator(); it.hasNext();) + result += it.next().compareTo(it1.next()); + return result; + } + + public boolean hasMetaData(){ + if (points == null) return false; + return true; + } + +} diff --git a/src/eye/models/Place.java b/src/eye/models/Place.java new file mode 100644 index 0000000..17f9140 --- /dev/null +++ b/src/eye/models/Place.java @@ -0,0 +1,48 @@ +package eye.models; + +import java.util.Date; + +/** + * + * @author gpdribbler, spr1ng, stream + * @version $Id: Place.java 24 2010-06-30 07:43:45Z spr1ng $ + */ +public class Place implements RemoteSource{ + + private String url; + private Date date; + + public Place() { + } + + public Place(String url, Date date) { + this.url = url; + this.date = date; + } + + public Place(String url) { + this.url = url; + } + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + @Override + public String toString() { + return url + " " + String.valueOf(date); + } + +} diff --git a/src/eye/models/Point.java b/src/eye/models/Point.java new file mode 100644 index 0000000..cd99804 --- /dev/null +++ b/src/eye/models/Point.java @@ -0,0 +1,86 @@ +package eye.models; + +import java.awt.image.BufferedImage; + +/** + * + * @author gpdribbler + * @version $Id: Point.java 24 2010-06-30 07:43:45Z spr1ng $ + */ +public class Point { + + private int x; + private int y; + private BufferedImage image; + + public Point() { + } + + public Point(int x, int y, BufferedImage image) { + this.x = x; + this.y = y; + this.image = image; + } + + //TODO: вычислять расстояние с поправкой на рубежность точки? + public int compareTo(Point p) { + int result = (x - p.getX()) * (x - p.getX()); + result += (y - p.getY()) * (y - p.getY()); + return (int) Math.sqrt(result); + } + + public boolean isBorder(int limit) { + int diff = 0; + for(int i = -1; i <= 1; i++) + for(int j = -1; j <= 1; j++) + diff += getRGBDifference(new Point(x+i, y+j, image)); + diff /= 8; + if(diff > limit) { + return true; + } else { + return false; + } + }//isBorderPixel + + public int getRGBDifference(Point point) { + int rgb1 = image.getRGB(x, y); + int rgb2 = image.getRGB(point.getX(), point.getY()); + + int red1 = (rgb1 & 0x00ff0000) >> 16; + int green1 = (rgb1 & 0x0000ff00) >> 8; + int blue1 = (rgb1 & 0x000000ff); + + int red2 = (rgb2 & 0x00ff0000) >> 16; + int green2 = (rgb2 & 0x0000ff00) >> 8; + int blue2 = (rgb2 & 0x000000ff); + + return (int) Math.sqrt( (red1 - red2)*(red1 - red2) + (green1 - green2) + * (green1 - green2) + (blue1 - blue2) * (blue1 - blue2) ); + }//getDifference + + + public int getX() { + return x; + } + + public void setX(int x) { + this.x = x; + } + + public int getY() { + return y; + } + + public void setY(int y) { + this.y = y; + } + + public BufferedImage getImage() { + return image; + } + + public void setImage(BufferedImage image) { + this.image = image; + } + +} diff --git a/src/eye/models/RemoteSource.java b/src/eye/models/RemoteSource.java new file mode 100644 index 0000000..b65b159 --- /dev/null +++ b/src/eye/models/RemoteSource.java @@ -0,0 +1,17 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package eye.models; + +/** + * + * @author stream + * @version $Id: RemoteSource.java 24 2010-06-30 07:43:45Z spr1ng $ + */ +public interface RemoteSource { + + public String getUrl(); + public void setUrl(String url); + +} diff --git a/src/eye/net/.svn/entries b/src/eye/net/.svn/entries new file mode 100644 index 0000000..ad4083f --- /dev/null +++ b/src/eye/net/.svn/entries @@ -0,0 +1,62 @@ +10 + +dir +28 +svn://localhost/spr1ngsvn/TheEye/Eye/src/eye/net +svn://localhost/spr1ngsvn/TheEye + + + +2010-07-01T05:35:24.601857Z +28 +spr1ng + + + + + + + + + + + + + + +8763ed6d-9318-4032-b958-c511fcb819a9 + +InetUtils.java +file + + + + +2010-07-01T05:00:24.026572Z +e7f202cff15cf5967def79b7b9e210de +2010-07-01T05:35:24.601857Z +28 +spr1ng + + + + + + + + + + + + + + + + + + + + + +1910 + diff --git a/src/eye/net/.svn/text-base/InetUtils.java.svn-base b/src/eye/net/.svn/text-base/InetUtils.java.svn-base new file mode 100644 index 0000000..787c29e --- /dev/null +++ b/src/eye/net/.svn/text-base/InetUtils.java.svn-base @@ -0,0 +1,68 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package eye.net; + +import java.net.Authenticator; +import java.net.PasswordAuthentication; +import java.net.URL; +import java.net.URLConnection; +import org.apache.log4j.Logger; + +/** + * + * @author spr1ng + */ +public class InetUtils { + + private final static Logger LOG = Logger.getLogger(InetUtils.class); + + /** + * @param host + * @param port + * @param login + * @param pass + */ + public void setProxy(String host, Integer port, final String login, final String pass) { + System.setProperty("http.proxyHost", host); + System.setProperty("http.proxyPort", port.toString()); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(login, pass.toCharArray()); + } + }); + } + /** + * Определяет, доступен ли удаленный ресурс + * @param url + * @param timeout + * @return + */ + public static boolean isReachable(String url, int timeout){ + try { + URL u = new URL(url); + URLConnection conn = u.openConnection(); + conn.setConnectTimeout(timeout); + conn.connect(); + } catch (Exception ex) { + LOG.error(ex.getMessage()); + return false; + } + return true; + } + + /** Определяет, доступен ли удаленный ресурс */ + public static boolean isReachable(String url){ + return isReachable(url, 500); + } + + /** Полезен при определении, есть ли у модуля доступ к интернет */ + public static boolean hasInetConnection(){ + return isReachable("http://ya.ru", 3000); + } + + +} diff --git a/src/eye/net/InetUtils.java b/src/eye/net/InetUtils.java new file mode 100644 index 0000000..787c29e --- /dev/null +++ b/src/eye/net/InetUtils.java @@ -0,0 +1,68 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package eye.net; + +import java.net.Authenticator; +import java.net.PasswordAuthentication; +import java.net.URL; +import java.net.URLConnection; +import org.apache.log4j.Logger; + +/** + * + * @author spr1ng + */ +public class InetUtils { + + private final static Logger LOG = Logger.getLogger(InetUtils.class); + + /** + * @param host + * @param port + * @param login + * @param pass + */ + public void setProxy(String host, Integer port, final String login, final String pass) { + System.setProperty("http.proxyHost", host); + System.setProperty("http.proxyPort", port.toString()); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(login, pass.toCharArray()); + } + }); + } + /** + * Определяет, доступен ли удаленный ресурс + * @param url + * @param timeout + * @return + */ + public static boolean isReachable(String url, int timeout){ + try { + URL u = new URL(url); + URLConnection conn = u.openConnection(); + conn.setConnectTimeout(timeout); + conn.connect(); + } catch (Exception ex) { + LOG.error(ex.getMessage()); + return false; + } + return true; + } + + /** Определяет, доступен ли удаленный ресурс */ + public static boolean isReachable(String url){ + return isReachable(url, 500); + } + + /** Полезен при определении, есть ли у модуля доступ к интернет */ + public static boolean hasInetConnection(){ + return isReachable("http://ya.ru", 3000); + } + + +}
rheaplex/postscript-viruses
bd21fed1810aebbb0a39cc8617a6be1b3ba0d4cb
Changes for Crypto Anarchist Manifesto infection.
diff --git a/2024/Makefile b/2024/Makefile index 723cea1..894c339 100644 --- a/2024/Makefile +++ b/2024/Makefile @@ -1,19 +1,49 @@ +.DEFAULT_GOAL := all + abstract-1.pdf: abstract-1.ps gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER \ -dDEVICEWIDTHPOINTS=1250 -dDEVICEHEIGHTPOINTS=504 \ -dPDFFitPage -sOutputFile=abstract-1.pdf \ ../2023/payload.ps abstract-1.ps abstract-2.pdf: abstract-2.ps gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER \ -dDEVICEWIDTHPOINTS=1284 -dDEVICEHEIGHTPOINTS=530 \ -dPDFFitPage -sOutputFile=abstract-2.pdf \ ../2023/payload.ps abstract-2.ps abstract-3.pdf: abstract-3.ps gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER \ -dDEVICEWIDTHPOINTS=1308 -dDEVICEHEIGHTPOINTS=500 \ -dPDFFitPage -sOutputFile=abstract-3.pdf \ ../2023/payload.ps abstract-3.ps -all: abstract-1.pdf abstract-2.pdf abstract-3.pdf +# May 1..3 have been superceded by: + +may-4.pdf: may-svg.ps + gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER \ + -dDEVICEWIDTHPOINTS=600 -dDEVICEHEIGHTPOINTS=500 \ + -dPDFFitPage -sOutputFile=may-4.pdf \ + ../2023/payload.ps may-svg.ps + +may-5.pdf: may.ps centred.ps + gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER \ + -dDEVICEWIDTHPOINTS=600 -dDEVICEHEIGHTPOINTS=400 \ + -dPDFFitPage -sOutputFile=may-5.pdf \ + ../2023/payload.ps may.ps centred.ps + +may-6.pdf: may.ps row-by-row-left-to-right.ps + gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER \ + -dDEVICEWIDTHPOINTS=600 -dDEVICEHEIGHTPOINTS=500 \ + -dPDFFitPage -sOutputFile=may-6.pdf \ + ../2023/payload.ps may.ps row-by-row-left-to-right.ps + +may-7.pdf: may.ps from-top-left.ps + gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER \ + -dDEVICEWIDTHPOINTS=600 -dDEVICEHEIGHTPOINTS=500 \ + -dPDFFitPage -sOutputFile=may-7.pdf \ + ../2023/payload.ps may.ps from-top-left.ps + + +all: abstract-1.pdf abstract-2.pdf abstract-3.pdf \ + may-4.pdf may-5.pdf may-6.pdf may-7.pdf diff --git a/2024/centred.ps b/2024/centred.ps new file mode 100644 index 0000000..0ec0f12 --- /dev/null +++ b/2024/centred.ps @@ -0,0 +1,32 @@ +%!PS + +/pagewidth currentpagedevice /PageSize get 0 get def +/pageheight currentpagedevice /PageSize get 1 get def + +/vcentre fontSize 2 div neg def +/hcentre pagewidth 2 div def +/voffset pageheight marginSize sub def +/hoffset pagewidth 2 div marginSize add def + +rows { + dup type /stringtype eq { + gsave + hoffset voffset translate + hcentre neg vcentre moveto + show + grestore + /voffset voffset fontSize sub def + } { + dup type /arraytype eq { + aload pop setgray pop pop + } { + /fontSize exch def + /vcentre fontSize 2 div neg def + fontFace findfont + fontSize scalefont + setfont + } ifelse + } ifelse +} forall + +showpage diff --git a/2024/from-top-left.ps b/2024/from-top-left.ps new file mode 100644 index 0000000..2ed17ca --- /dev/null +++ b/2024/from-top-left.ps @@ -0,0 +1,27 @@ +%!PS + +/pagewidth currentpagedevice /PageSize get 0 get def +/pageheight currentpagedevice /PageSize get 1 get def + +/centre fontSize 2 div neg def +/offset pageheight fontSize marginSize 2 mul add sub def + +rows { + dup type /stringtype eq { + marginSize offset moveto + show + /offset offset fontSize sub def + } { + dup type /arraytype eq { + aload pop setgray pop pop + } { + /fontSize exch def + /centre fontSize 2 div neg def + fontFace findfont + fontSize scalefont + setfont + } ifelse + } ifelse +} forall + +showpage diff --git a/2024/may-1.pdf b/2024/may-1.pdf new file mode 100644 index 0000000..b96d63c Binary files /dev/null and b/2024/may-1.pdf differ diff --git a/2024/may-2.pdf b/2024/may-2.pdf new file mode 100644 index 0000000..9517784 Binary files /dev/null and b/2024/may-2.pdf differ diff --git a/2024/may-3.pdf b/2024/may-3.pdf new file mode 100644 index 0000000..b06b635 Binary files /dev/null and b/2024/may-3.pdf differ diff --git a/2024/may-4.pdf b/2024/may-4.pdf new file mode 100644 index 0000000..dd03238 Binary files /dev/null and b/2024/may-4.pdf differ diff --git a/2024/may-5.pdf b/2024/may-5.pdf new file mode 100644 index 0000000..1e54ef4 Binary files /dev/null and b/2024/may-5.pdf differ diff --git a/2024/may-6.pdf b/2024/may-6.pdf new file mode 100644 index 0000000..89bdb0a Binary files /dev/null and b/2024/may-6.pdf differ diff --git a/2024/may-7.pdf b/2024/may-7.pdf new file mode 100644 index 0000000..e29ae52 Binary files /dev/null and b/2024/may-7.pdf differ diff --git a/2024/may-7.png b/2024/may-7.png new file mode 100644 index 0000000..f1e3620 Binary files /dev/null and b/2024/may-7.png differ diff --git a/2024/may-svg.ps b/2024/may-svg.ps new file mode 100644 index 0000000..380d12d --- /dev/null +++ b/2024/may-svg.ps @@ -0,0 +1,645 @@ +%!PS-Adobe-3.0 +%%Creator: cairo 1.18.0 (https://cairographics.org) +%%CreationDate: Sun Nov 17 16:37:30 2024 +%%Pages: 1 +%%DocumentData: Clean7Bit +%%LanguageLevel: 2 +%%DocumentMedia: 200x200mm 567 567 0 () () +%%BoundingBox: 77 121 490 446 +%%EndComments +%%BeginProlog +/languagelevel where +{ pop languagelevel } { 1 } ifelse +2 lt { /Helvetica findfont 12 scalefont setfont 50 500 moveto + (This print job requires a PostScript Language Level 2 printer.) show + showpage quit } if +/q { gsave } bind def +/Q { grestore } bind def +/cm { 6 array astore concat } bind def +/w { setlinewidth } bind def +/J { setlinecap } bind def +/j { setlinejoin } bind def +/M { setmiterlimit } bind def +/d { setdash } bind def +/m { moveto } bind def +/l { lineto } bind def +/c { curveto } bind def +/h { closepath } bind def +/re { exch dup neg 3 1 roll 5 3 roll moveto 0 rlineto + 0 exch rlineto 0 rlineto closepath } bind def +/S { stroke } bind def +/f { fill } bind def +/f* { eofill } bind def +/n { newpath } bind def +/W { clip } bind def +/W* { eoclip } bind def +/BT { } bind def +/ET { } bind def +/BDC { mark 3 1 roll /BDC pdfmark } bind def +/EMC { mark /EMC pdfmark } bind def +/cairo_store_point { /cairo_point_y exch def /cairo_point_x exch def } def +/Tj { show currentpoint cairo_store_point } bind def +/TJ { + { + dup + type /stringtype eq + { show } { -0.001 mul 0 cairo_font_matrix dtransform rmoveto } ifelse + } forall + currentpoint cairo_store_point +} bind def +/cairo_selectfont { cairo_font_matrix aload pop pop pop 0 0 6 array astore + cairo_font exch selectfont cairo_point_x cairo_point_y moveto } bind def +/Tf { pop /cairo_font exch def /cairo_font_matrix where + { pop cairo_selectfont } if } bind def +/Td { matrix translate cairo_font_matrix matrix concatmatrix dup + /cairo_font_matrix exch def dup 4 get exch 5 get cairo_store_point + /cairo_font where { pop cairo_selectfont } if } bind def +/Tm { 2 copy 8 2 roll 6 array astore /cairo_font_matrix exch def + cairo_store_point /cairo_font where { pop cairo_selectfont } if } bind def +/g { setgray } bind def +/rg { setrgbcolor } bind def +/d1 { setcachedevice } bind def +/cairo_data_source { + CairoDataIndex CairoData length lt + { CairoData CairoDataIndex get /CairoDataIndex CairoDataIndex 1 add def } + { () } ifelse +} def +/cairo_flush_ascii85_file { cairo_ascii85_file status { cairo_ascii85_file flushfile } if } def +/cairo_image { image cairo_flush_ascii85_file } def +/cairo_imagemask { imagemask cairo_flush_ascii85_file } def +/cairo_set_page_size { + % Change paper size, but only if different from previous paper size otherwise + % duplex fails. PLRM specifies a tolerance of 5 pts when matching paper size + % so we use the same when checking if the size changes. + /setpagedevice where { + pop currentpagedevice + /PageSize known { + 2 copy + currentpagedevice /PageSize get aload pop + exch 4 1 roll + sub abs 5 gt + 3 1 roll + sub abs 5 gt + or + } { + true + } ifelse + { + 2 array astore + 2 dict begin + /PageSize exch def + /ImagingBBox null def + currentdict end + setpagedevice + } { + pop pop + } ifelse + } { + pop + } ifelse +} def +%%EndProlog +%%BeginSetup +%%BeginResource: font f-0-0 +%!FontType1-1.1 f-0-0 1.0 +11 dict begin +/FontName /f-0-0 def +/PaintType 0 def +/FontType 1 def +/FontMatrix [0.001 0 0 0.001 0 0] readonly def +/FontBBox {-17 -235 850 785 } readonly def +/Encoding 256 array +0 1 255 {1 index exch /.notdef put} for +dup 32 /space put +dup 44 /comma put +dup 45 /hyphen put +dup 46 /period put +dup 65 /A put +dup 67 /C put +dup 73 /I put +dup 77 /M put +dup 78 /N put +dup 82 /R put +dup 84 /T put +dup 97 /a put +dup 98 /b put +dup 99 /c put +dup 100 /d put +dup 101 /e put +dup 102 /f put +dup 103 /g put +dup 104 /h put +dup 105 /i put +dup 107 /k put +dup 108 /l put +dup 109 /m put +dup 110 /n put +dup 111 /o put +dup 112 /p put +dup 114 /r put +dup 115 /s put +dup 116 /t put +dup 117 /u put +dup 118 /v put +dup 119 /w put +dup 120 /x put +dup 121 /y put +readonly def +currentdict end +currentfile eexec +f983ef0097ece636fb4a96c74d26ab84185f6dfa4a16a7a1c27bbe3f1156aea698df336d20b467 +b10e7f33846656653c5ac6962759d3056cbdb3190bac614b984bf5a132dc418192443014ba63de +800d392b6fea026574bb2535fd7bb5338f35bf15a88ea328fdaa49670c7852e3d060f3c5d6b07f +2ef6d0f22646c5d18e19a2ae3ee120390f6dd96f76dcf1e127de5e9299077a00c17c0d71e36e5b +9d5ec58fceda57739a6a4214d4b79d6c48d2784b60c320323c7acddddf34db833cac0cf109f799 +69d114a330d372e5c978a66acc84e3fe5557f6240856a013ffaa0199444e5c5036f775eba4a5c5 +8cde66cf604b9aca2178431127b8a1ff7ed633a65c04600af5f573483112251cae05fadec936cc +8dac7a3f8a3ab1bef3a39aef77c611866cd434afd8fb561e7dbcc773cdaa6f7f48129b4aba99ea +a4d1c367bb06073b71aaab7a10352eff21851517940aa9083a8228fe2eb0a551c35e070a4ac7a6 +41cd475a4ab2ca3381e517fe1522dc704b1b380f7f2379beb87796ccd6532a20349bf46ef7e92a +83d2dd15bb206be5e25f4cf32ba51febff94618a10b0fab2966d7f181a2b499b326918bcb4d402 +70606627b118b70d54f4b18510f6f3b6866e0812923f0e0b20738eb00780453d4cedc3e01a1e4b +e57d4d687678f1dd3fb0a6cebf2122fab9b31d6f60d92459eb613da53ee136cf6ef51d9f0ff5bc +4d1cfcec5c3fe4d0346e0b491f9cc18f6d5662baf545c670e986bea2860c33d4f30a426e504e8b +3c7f31f1f369aa43ba8dd4023879fd9030d6e5f7330d665df6ee218a42081e479906b18ac7095b +4a64cc8ae98c30f64fde7715c559f89f75a7c16ef9bea13f6ebf6580c629a7592a159b7e027fab +986f58079f3a7a95566f30f446c497ce39d722a1f6ecb701663a01005953ab6f65123a24689427 +390b84d0c6c94f5c004bcf019f051278c87b309363368a31f30562028819dd35e556584b970927 +77246b6c28b7981363447277f3eac84f23eac5e3ee2f1fe3cefb9a59cfcd7c52a0c814cbbfe48f +36d6014dd81a473bf271c8da6a093ed7765e9e20ba77ccdea17f79b4ca85284aa8ebee4fb4f5a6 +9da060af2271c47328a0321b79fe42272529c556e5845f87f111aa9cfa444fb7457e786ad5be6f +680b3e202e28b2e1e2e5d3ada3a285ce072741a4af70597b066661d0bf5541eebe4d77974be667 +90e79f7d11c773b1d9085d802ac1ddb638299c1caf1ab01519a934c491bde15486bd8ec0dbcf4f +6ae21e872c6ac81afeef46f87ee4651067e26d4fd77dca7c8e7879d7974406b3d3d337ee5e24b2 +6d914bcf5dbc2412170cf684df90507143db358279ee91529f5beec2730a45220a536a13881435 +dcfa24fd1df4816586bba5be52df5bc2a17717d30f674f3821fb3570365ef313df1729fb3a24fa +4e7d15cbf01b23ae76747ba3f05b69d55fbca1cc2f70240d863b923ff544bd0ad218573eaf4e50 +a7fea614adf7735722bc925a8be7270bfad262f634b423379ae2a550d32f7e9555e7f4727dd4f0 +790fabe7c1e83225a3dbc5d0a23358a5f1ba1eca36bf78bbc6d412a98393369799dba58a6c5355 +89ab81a0dd8ec7fae48623d5f64565b0d5a899bdfae7c14cda1a2e6bffb20896f3e3998bbc34aa +826dd0062b4a3626b466ecb1980f8b669f3765077949ba6cbaad7dd7d048b08767c6ad966bbb11 +4ed77186f08146f77fe71f28614637841339756b90fd68b92ee9d7995fc5c549bbfde6a6ae46f5 +8cff0d31154d264e2e38310b91fcac48c94dd5c4caa47f684bf324ec2932d5ac28333635a8a43b +f660c435ec2a60cd7bf7b6475eaf8c01b9e26fd182da1023e325917fe51d382cb04dacd5ea6033 +5a2d262a7e5c2f5dc6079259d9c8a5cfb23affee70b85713f183094f4073507b18eded6369e94d +65f313d7500debcedeadc997b3fe3d863bd1fe8bfa097279ede15a658996dcb686d38691c72381 +834cf2c37f804047d796cd58a72e9a6f19f6f58ed037e38af617f602251cbdfc073e44e6eb61dd +62320496edc2d021b414d3155c81b2a7ab407b982c14ca2d4d129037c7d2a36bb771c155968d9a +dd656aadb78d608c48165733a4e0353b519baa55ea74c6c7dbdbab796dc3502a0e66b5b9799e65 +a78498d5c5c66ae3e63dc7fc7c06f6ab4fc4fe3ff47e56bde4c93a882cca26ce00d67775959321 +f4357670e16dc811e3e6877ad721afb34c12643e77ed56b0c7244c26ed6eea47c35ad5f208a644 +1fda49224d813d41d9fdf9dd0976b3536ee84264b68b00486b44426f494b6c5ba4cca9cb53bcbe +8d6e0f068f0fca411883711119ebee83bdff877904713b2cabc0af4ba11ed42e1100e94fc53add +e6e887844c59c1e08e6ebd77ad3d0544cbbfb45c2be9df217be285cf6bb1a715bb121a274a21d5 +7003555f28ee0398a85ca62e8833f13c8762229b43ed4b84217b71565ded7c4e37265cccdb7175 +413ec9c8947326c70a6e9f96f9885bf03141a751d834fa4f0d12c35145e25f57fefc8c9492171d +bf9964bbecb8427e69f9eec2a07277191889f20f7602519a93606e26fc99bf9b7ee47e77b956e7 +db1a322c47779d7657ddc6aeda7a65509473f4e0e09d514d7b47d5ce4e546de0a8e193e3b77658 +5c8b32e0ce493dd23d03168bf3381922df7f53ef013d3e2d86f0a8b1cc2fdc5fb1b7258e156778 +6bf3f0ef0a903bf25acae9ffa369d889f49e6a866fbeb567edeeb69f1eaf891e3b727d82a943ed +ccb0484964a8644b1942310d0908d13fa6aa11aeacf780868d6054c276628622b9261f73adbbb3 +c2b34cae84cb090614bfb9dfcabe9ec9608579ca3239981e36150cca2d0cffff02ec304e22315a +61226acc43ea3a589d7f5d9546f6504ee0584c69507746cd9ce2e66fa8c40760465d2b62653185 +903220e3b798cbd73a6ae395e7bb2d0fc054c9ea385df5f16a8115f5bf01fb50e410b8190cf334 +7c0bbbae16ec6e17dc26dfe0e2bd72f6b5056f3152cb560d4e321ca8c0b4627277b52869070cfe +1da48a49ed4f5c0e1e341e173784900699e6cadb59008db4cc2a5def3295003b4899c62e686843 +92783cbd4c996fb98db706dd1430fc2b9655046f460cdc03406f78b60eea3bc63dcc1aadbc5cb7 +1e39ae4b83164f61ea9fca5dcc5549d0997048f616c1c1d9d04f875bd82491d629aa725ccee839 +71a977c820fa8d56b80d94991f672cf24ff6b37083642d738440856e7b0660b61471bcce481697 +00a82b87a5e2402ca15adf96a40f9bb0cb3e08cb2edbb0230b10d664d6a610830076a0a5a0d880 +036e1c34da3d5a6f8369028ccb95f0fe2096abb760ee438e31b454f62547017342d5d36abd400e +64ed0f1c308143e6d9b8828d413df55dc15b0723a2ddc3f13fc8024c51e8d993c1fb22c059f61d +25793a9ff0061ae8729bce4a6d13243df101b7c8debac5a8396e4c95d84507cbcad2341d468a40 +297bd0828f4acb3c4435c1b86ccd8518fb92d788d05a033662263a5fdda043998f3e373cdf8cb4 +24ae33af236b2856d14b9d257adf40887612bd3f5e9cfa090f430c81d8cb12dcd2d6efb6f7f62b +0b83e3fdc96e9b466580dc1727772ae7d7cec5e34dc8aab7b879ba1c8b55cb94f53beff5ff1f01 +4269917e33937d94613d5484688d3ab1db5ccc7cd2eff477e6096c0e0ce0e889f0fc707e8c9576 +8aa879f926c07b8637e0499898d71f4f7da985b51273eda252523d0f896bd3e6dbc81858c25e0d +cbc65d8168714379ddaa3e1bd4000cf499253c590c4b21e6f403ec048ebd11350e43b86a646307 +c55a11eb136c6aca67eb1499c5a8d6603202dc19fe63a7ad96af7714d0d02b30fd4d7f2d1142d4 +a21a252f84dfdec880574721bdd698916ce1fbf802742219ddce907c83cc0858113d5d958b1c22 +fd9e5c160c86ffe2a67fa972fa64a00f3ef27e8cceb76dce28860e759310cadc1b589da5da32dd +c7ea23a1056be36c096688378e62aeb7e5da8ddf77f94a756c729418abf165cac2400acd41c7f9 +288a8b55bdd731a68d7713ae68a190ed23601a714210478214dd95099fb998b30fdc48abd3c779 +4ca4bc9c452888b7ad3cfa0631de8920bdbdf5c64f7d7eb19601882e67af317660c040ff86f555 +cec542f323402dfdc0890a42965ac90610d7978169ec4dbc5f16b3f45bae96a63cc0bb63f00677 +84d5159dad88886bbcd28c111cda84744c64808aa345f46594e41ac85c1da47e49c18dc68f7811 +ae3a5f434f125a574856f197063f950bb84310c15d11a7dba16151ff3e8ee2a8213df311e93d3a +b6cccb23390d04821aae5dc911061e07128abbe8a6b4361ac677f134d1ce328dd086e5a84c09bb +5f5bef6688fd9ad25d0a124a7191fe80443cfda4f47fe5fb4db6c8687ce640133bc07cb8d86a99 +447e6dfd1ba0e3be5fe620d60028ed5d6e9b9fded798a37020a430b81f6b3fa0bd82cc917533aa +3322fa4044c02d5678a4820ce7e74cb723e3a0c27aabeebdbf3b02eefc9cd9ca093ee0b4492f5f +c6e3c970543a89db18a02c85cd391a0c51a145ec5522cd07bb5fcbb08f62e0784cd84ac61e187a +e5c925fe55e4a27c21926d741db4d5ad90404f2f4405e83c8e43b6e694f67b92b0c20de9956231 +7b37c35ce22eb8119b86c18260120e01ddef1bd643c90febb00840fbc86d54a5234cd983d4fdee +3a208be067470f533075e1bed98045b07f11d5ed9d7ad465e7daa18754a426e3651cb6fcae4798 +f9d25d30d5107cde1272991c58b7a3b015fcf7ac4266026f3fe24288f00e5c7917ec06ad0e0b22 +7fa9e765607941a1914e03e80092a8e096f0b6ba655d54396ff16ea1af0d72d7eb56bdb9c932ab +d4a6204fa73c78b653841cd1a2e94225ec6ac1a2a65e00d18435b477ef2a5217b86404fee4c42c +adb6af2f78da3e48912dd3aa8bb148628bab307696ffb3df54182784376ec5a6ad6cb04df67902 +ef1d85b59e6135368d933634c616c7b933e727723c2aecd409f96165b7cca02850d3491ff9b66a +1ea18a7897202039249a8330517b2b05c339dff2d677c278c2b369296b3a93587a68b55c3e037f +fe090c14159bb5ea6fcc93804ca9e74b916ca040f1825c0cdbf3f9f219af868dab2fddb7f14d25 +6c69b2e580e5643b5b7231aaf7a46ef9167fcc66a46e839e8ddf96fa7ec31d92a281b8057c327f +f4790e69f6b000535377e9cb4b5a811b0964e393d235a9594941e6261773c8fbcba570c5e6edb5 +e3100d010a16695d77e2754b1996accc4eeb716a13c781c6cd98a38337d3b82fcb9abf14f7f001 +3b09a95577586c74090f41071bd7f3cb81fa934298ad47dd91b50d268ee8568dc0d2fcdf231ce8 +de5ecaf660edfd87dcaf744d77f9c325674bdabe3ccf10b6dbbbf0f6d60b55cf20c5629792ec70 +ea7996ca2788bce1c992cdc427182caa28f8a8d4a3fac0bca8e3b0eee5603cbe5cf2608cc9e423 +90cf8818e39fcb3693b050ed3d216684a8753ecc78134cef026590883f3adaeddd93133647acf2 +3f49df4d1dc8fbaf674bbb79d8cb78108ea24c570bb745fd266d880ed1fd85df2d59e7ba35b34e +b84bd53cae902f6ec0409c6d58fa79adc8c7cbaeb8959bfd8107949f75aa344445feb62e7b08ba +fce20ecd26f4e0ff91cc8ec910572be63560c7348ca37953f3516362ba579a2d08583ed66ebde1 +1603dd2a1b6406220a1d85668a627afa228dae841bfa091a4b9d60dbc6d14780abd266c6fa7ac4 +f22e5703c8407357899a9f886f13b3eacd5c3bf9213267e079d7a03ae432ab48db01087ea07f0c +2fcb9a5bfecd6841d2fc791c541a06f5a21e2ce7f40f8ae0a72273f8e93493cc1fccc96d9edc30 +1fc5d87e5ffcfe532882bfa91a8b74bebbee16fb7728e6872d26a783a5fc137b344d61f93df7ef +50c2110ade0eb694904111d77b50a5544a617aa19bf137d6754963b9c05c3b414962cfe42467a5 +6b71d80ed8c0cf4e66170827622967186d22dcabf77ce7cbf23c4ae884086f0e82667b63ddcf1a +b23dd23400f0bbac06a20cad68f6aa16f16479ab9b135e6b08f9c2654d3ccbfb737174f6d16c6b +2ab59e7090f9f0e30f8fa94290a98826077dd06080138c21dc964c31e8348b8cc631094707384c +4e7143a2c757a71182c4f47e0fd43108bd18da8559d7632b728fcfef82c50f8519b404be27d1ac +ad746d70e1373bb5a98d9ea8f19928f7e525ffbaf6b8c8a8c588a0f76af60aec1731b4d6b75c15 +8aadbebb850141bd3d97599b09d7b0816a21ef09969e4c79bdf3c80e5ead149f0a5c851090c9d5 +b73e7555f87cd25d4d153d568de8d9ce3ab639a2e21b6dec7787f25b8fb7f7545e867a0f212694 +25da63ebb56995ed407422423e08d0dd2ba092d49b74c9981ed5958f8c91f39caaa37cedf28e1a +5e356956ec037020689a7374c1311de3e23b7b48c78e3a1cdbad2c2265b8269d812e6faa3ef26e +448f9e60574bf07f0e809e386b1a949f9f273c216b3b4ea9957bafd7efff99b53ce42fe4384952 +78ae4d31735e3fa4f02df86e6ef96902668704a8a11d04789ebbd63c38f5c89120521dd9fda5cb +d2e4f96be6b86c286bbb10f97657a058d7e28fae0adc5664db7480380c1469fa10beeb99b9e11a +6721c928d502bee7f35f39be41a8bf8a1079e32b2d9e54c7b53ee5aee174bb1c409afd71d90784 +aa4c053e9be77a8da51cf27dce83cc520a53cad5ca35a555ac5fb2ef6b02ce8ec9473e3f5a2e2e +0f31bca8ad053797f67e852db3fa36eed26c76323ad3be77c5a403589e4f635d4818ddcaced711 +6aab09d58dd33a746736d2585095eab20aad13e2eed8a73f34ede6151bf42a4626aeb41f21e33d +a1f1ded513c90b7e62081c6b6b682b2d9cfacb5fbfef16af568ffb20018521c43cc052193678fb +368f41f0f1a88dabfe188ecaf712017f9726da53b6e17ff79a9232fa353f95d4019cd87273686c +85fcef7fcec13fb5f18a6110e09a2752932655ab5433ac1971c9671ed067f0e9c8d61ed6866b59 +765d7d32eba188a53016b91dcf13ab7cf174cebc2de2ff3a8fdb5433f1bfa1fa8ca41481bfe827 +a8c91623d9e2ef5a753223c0b3c21d1b65a8f6c462f9243a6bb440b3f625ca710f30eae1b3f9e4 +8f0859bd0543d2bf3392e4d5b7df634064c9afc667539e41ce9c373fc37a19ab4309dd90e531cb +995eb360facd0defdba6df4bd36395ad528795262a2996688f799517ff9bdfb951f0059b80cf51 +e989cf3c340b33f8b0d094ff45160c2ffc0000bebc1d94707ec307889934c48f13da6e56abbf08 +2d67fcaf4ea10ca35a183e529c1372d626e32a8d9c00348787c36481229891a689023dad61af40 +52a167d3ab8127bbfbc57325e15b7646fb83f539dd0a213487d667a225733d644227e5b5caccd7 +c311b1af52a90845bdb85ff37e9ac9294f6a118220b129ea9c1fcc73bc7d9cf48f0b29c43fdbc4 +20c021b5d1a87dbdc8ca9499f633bea67aacd18404c1651c62f0a614a18074602ac5daea90a65d +2373d9888afd8d9b70a4f84c1ad48f8b63525a39ef0f9cc809f3783cdf33470d6a0743f0db8698 +a1101d9931c909e3cbdab6756d7e8ab679d2f8f8902f3a75e836043e60de035524013803fa4644 +015362c223801dbf7d00be13561fcd10d8bbcb6b0dc60f6002827051db18e943aaeb4ae4b7731b +bc87ad92c1aee1044eef16f8511a6825157aea2a1d76df7d5907804149fd6503e2d8f188df42e8 +4ff5aa470889f71dbb8ba565f8c1b726dc52844e1b8fc20c53974fc9ee11beb29b5d01d8544433 +3736fec8c01b49c1e657e7284378f706416c6dd7c55a1c9968be03a08bd90f3ae8d438702f25f5 +e6d7bd27a27c593617253bf37c6497e3482f03353dcdee1b1cd38d3324966da3cd5f8a9c560826 +4350ac39da1d88116e0c9b01cec9bea69de268da890bb5af2c2ee236a254efc20f35c0cdc8d35d +936680eee235bddb6cff98929cb57cbaf25d275cb8944482536baac13777268c279c87cb8e84e1 +426d6257c1a64d094c156dba9f5191de003cffb7e1f55fccf8327a1178b95e72a4c184cf334aa0 +f8ffc71c3be9498f61e8c572f1fc225b8689d74f09e815a457cfbba4a15f5b44e49b3a8812d8ca +8450e30b6cf2ed1ad64da0b3a66a9afdfdd981bad13e3dd5e88ab601720cb84756ab241ce31b75 +1d858f002657f669bc471c165a5d4c1e4fad9b73018d307d83ecfc1d969d5416bfd2fc1051e592 +d423d3a9efcc9c3434c2fb03736f59329a90725df79200804f884c767398bf9858c6a8e8642df3 +bad68612864ceb6f55aba0bb55a135c153e5ec6fab6a5ce2e9d89f7d18c9216717b0883b3b045a +dd04af7f1ecfb9788f34e0a1e8a206bcf44542bf71a83f62036ec6c68d6a91c215035061df9d23 +bbaf0d2a85bcc58d500462f77c091eda5741eeafb32f4b8dac04f129130844509e069bede630b1 +de1fac708966343b519e16a3e79aee1a6f0e6702d3098d367b2aa71f1461644099bacf9769419e +8c5fa3f258c7c679865cf6a2347f6ef5630d95f48420d9871d46287bb824256fb228b97156d41d +12a427f4c6a42d242b0dacadc5cb92119dd9c5233f8cc933f9429633b3b84f9b10459e33642211 +bf36b69e875c74cb1a184727d58ffc05a000d43ef4d36c3c6bfc447a832e89d6957a865b54edd1 +4ad08f07ea3e291346c9a68f28c0c6a568b87f590cc8ac8bf83ae5457a66390cc12c68a6e55e10 +f39d7778ded1fe60e8d49df2124c0d1f63e3f48addb69ca8941e52f9e55afe75855aab3f1f5137 +4d37c7637a56386a88e8456d86d0f82d04457b847794b628e785b19e1d8f7624dd73bc953e7d50 +2da1b6c488ab38db4af02112406e27a6badf9de043f78f31e6d431cea8dce093f7725788ae98b3 +3e45e0dfdc77fd57731c3423e2e356af1474e2d715c554c76fa3d56c61c334f2aecd41fd1b7489 +846095f3d74455f18b5c6bf4373ad8122f4e18fbbeed73a47cd5b34bc507604dee9070f1cfbbe1 +cdf7ffc3070f3944570e8f5bfe72683c95ade7fcdf2285948a916b09aabbf7ca64ee71b229e073 +83eff5583af4a40de914b02276009ae837db637fcad4a6d329b2030fdda20860b248e5e69ebe82 +dcd4a4389896afc3d0ff890907498b9cc66c2d6599c360527f844caf588f5932cd4eb7c818a9ef +4ad51e87bd8a0c51ecaae0359ce4ae6c44a6b4d0e430b32a1b5e4d11b32329afcc3f1a325aa9e6 +3cd50ffa327179772534f941a4a7e4accd0b97f4b78902c52edc0ac270108aa2ea7e4e7e83c685 +0b9aea012a9f021c32a1191b4955b18a271764e8ee623730639c3289b3535576fb18970dbc2d49 +290d2f56049a5bcd973a5b10bf824bdcff1fc7d411dd9c163aba32269ed40c2cd25e771100d392 +ce31b0ece678f0fca8ac84c9e33a08e993497ba6a4afceaf5593e0ae0a6e69316c147e4148f43f +ea21af2453310946088a4f2ca5681e094d4c62533fc52d88d6e214fcf807e21c659447604bb8fd +4d2e981a57676e073ac6a6815d87aec8af5b6bddbcb4c058f11bf7088ec037408ba74714ef994d +733f16471150e6ab6512a752e8c669cfceb755dec8c0266d888ed71436051a53f4a46775d77bbb +db256d2b211114820d888b5ee54d291e271831de200d63767d9f43cb873529bd5da67fc5c8555a +b358f7df313cdf6ba01e22def6af5ceb17f5bcfa3e58a19516c45d4887deaae7c4a81d08b74f11 +3f5f589fc87ee34ca4933effbc07c6bfbc2dcb159a79eea4494f637081a7596a9f278d7b49ada5 +e875434be59253453a7146ff0ba24955db793f116c9bc8983ad6b6561c15a27a400d58cbf26cac +8cb52535c12d299735c1cddc0dcd1148953c9fef75116ca98589e3abb31ba404ed5aae0eecc200 +574cc00168d541185b2596da6cc1d14184e4803174b77e676bb0c5b27738532de659147aba3826 +d9fbb1186d522480357a08c53df75617f727966162dbddea39a221424646794c6998eb768b4f8e +bb8fb4d31a00efc7c14325ba8ce5aed74196cffe47190e645f4406f189d93efc4267c2756aa019 +eb94ec07f71729e14d31e754cb136b8ae762980b1d8f24aca5634a2088c75ab02257a1ab61ea43 +33f469d1b384e239feedc18ac36b6b47629f6e90c8f910d945f4fcf3263a82441af55f7e1fad87 +186f8f83fe0c9a20e392681e2850e4d29e8272c852d39718f06ae2fac890d77d906eb9e71a555f +f1e9785d59180e94302fd6c94688e475c1ab93d839dc4f8e2aedeec389dfe81dc083b16e93e3bb +a868e415c6aadbd36c0facbc6623c78fc070618909b4ccb42153c0a3a56a8b9114f72fa9819dd6 +26f36ac19af2d0007e77e7fd7aa9d8aa70b67713f9a9109632c7b5ff4a27392e51d89a15e0e77f +d971d78e6b218aa8ab19fca624af25047d34db43818170449b00870e1b596adffe59765d69a65e +f15f766775439ce0f90e6c5df842262e439df7ee9ccf98e10d962d02fb7b90bde22f2e37ed4b3a +cb5fb32cf0e0fba01d8c1c576eed309d1b20729f47b6a6a0fb6e0bc3cbcc7b27d9612856498cc0 +1da785c0395a861f96c537226ea7de7440c6110452cc971aa8298edb0fc88a785a814dbb5f9045 +a24350e9f87322d84e867d3dc2cacddb2d6fcb45fbff3083b7dbaec5169644272efd7b305a35a4 +436589b40d37e420fb149a891ba2e9a527e1fcf44c8381478a90bcf71283502d16221b4680e2cf +70a64238a13ede0ae90588787443184dbae299b90bc0e2b1087a2541bb6288ee67abe73cc69c1e +90476f44d741349c18c7cadd831bd587aaaf1371e6860f1c8af4879ceaa373526c2bf0d711fbdd +b38d4aacbe486179360813cb755804c1be4d53447ccf9859114ba08246e53b0bc83886d32eedfd +61eb05f3d65dad5b6b6c52335b643314206387665558d9a251177229a550c4138c4927936d4c8c +d0ade745c261956555e65a549fda28c4d0da4db85691759edaaa6a2877f3e2be1e1415d1c7acaa +2e8e475cb17693c73aceaf19acffa8d3ed18361391316ed5f491e4477c39f50c52264db732a086 +a3a562d0c571f03d3dad3c126686f8bdaa549c1d42bf22bb12a93bea101cd388a02c136aaad431 +47fb8cf161b8de46d136de86a7b002733fc0813abc29db30928273f478a8809c421a2c5ff0cb31 +01f96510b873a63a5edaeb9ce0e13f9c92cb65f63c3a6d477e6a29a26a85f9715452ce736aea72 +f641764bb9c6b975931006cec8e64948f76d50381c68594f1fc860d909492836caa2843bcdc576 +e1f857da4aa18805b717371ec757bc12993d0505f369fffd7ef82d03c33b6901a861bb8b77ff34 +868ce133e682dc62bd93c10c9706b077c8131e386a1ac5060c00c2b42b9c478c8d971852c1c1c4 +d415ed608851338ec79cd6b8ce65e549fc418fd070d5e5f84e6dac10ee1b232dcb91847461e701 +4e0e9ddba9ed9a93ec73871bbf4751a7292d0490084ef992e1e1c5a28abd9c2aa55df154ac42b6 +1b28c67c8ee70f696cf4579242f2eae2c9d3c592775dac8254116bb7de6d37416c6c0c59ce1be5 +46e268005fc409cb430eb340849d17eb2fe3d360a4a6f5b44e0786fcf112c21e53335db09a01e7 +8be52878f01c77ff992fc365f6423dd7c203388bbb0c034307ab65cd7ce8e876a43da16c7abf09 +19680e89546b700aa7078f355bcf51b9643d53480e58b0333e3187aadef63d525c23e498191149 +4fb60000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +cleartomark +%%EndResource +%%BeginResource: font HelveticaNeue-UltraLight +11 dict begin +/FontType 42 def +/FontName /HelveticaNeue-UltraLight def +/PaintType 0 def +/FontMatrix [ 1 0 0 1 0 0 ] def +/FontBBox [ 0 0 0 0 ] def +/Encoding 256 array def +0 1 255 { Encoding exch /.notdef put } for +Encoding 32 /space put +/CharStrings 2 dict dup begin +/.notdef 0 def +/space 1 def +end readonly def +/sfnts [ +<00010000000900800003001063767420edf87475000000d40000003a6670676d37be51000000 +011000000439676c796668de5f4a0000009c0000003868656164f88568170000054c00000036 +6868656106f503960000058400000024686d7478030a0032000005a8000000086c6f63610000 +0070000005b00000000c6d61787002330531000005bc000000207072657082a62463000005dc +000000d600020032000001c2020000030007000b00b800052fb800042f303125211121251121 +1101bafe800180fe7801900801f008fe00020000000014001400140014000000100050ff0c00 +02020d00a8020e00ca02110000140014001b003200740014001600000011ff4f000b0202000c +02ca00110000b800002c4bb800095058b101018e59b801ff85b800441db9000900035f5e2db8 +00012c2020456944b001602db800022cb800012a212db800032c2046b003254652582359208a +208a49648a204620686164b004254620686164525823658a592f20b00053586920b000545821 +b040591b6920b000545821b0406559593a2db800042c2046b00425465258238a592046206a61 +64b0042546206a61645258238a592ffd2db800052c4b20b0032650585158b080441bb0404459 +1b21212045b0c05058b0c0441b2159592db800062c2020456944b001602020457d691844b001 +602db800072cb800062a2db800082c4b20b003265358b0801bb040598a8a20b003265358b002 +2621b0c08a8a1b8a235920b0032653582321b801008a8a1b8a235920b80003265358b0032545 +b8014050582321b8014023211bb003254523212321591b2159442db800092c4b535845441b21 +21592db8000a2c4bb800095058b101018e59b801ff85b800441db9000900035f5e2db8000b2c +2020456944b001602db8000c2cb8000b2a212db8000d2c2046b003254652582359208a208a49 +648a204620686164b004254620686164525823658a592f20b00053586920b000545821b04059 +1b6920b000545821b0406559593a2db8000e2c2046b00425465258238a592046206a6164b004 +2546206a61645258238a592ffd2db8000f2c4b20b0032650585158b080441bb04044591b2121 +2045b0c05058b0c0441b2159592db800102c2020456944b001602020457d691844b001602db8 +00112cb800102a2db800122c4b20b003265358b0401bb000598a8a20b0032653582321b0808a +8a1b8a235920b0032653582321b800c08a8a1b8a235920b0032653582321b801008a8a1b8a23 +5920b0032653582321b801408a8a1b8a235920b80003265358b0032545b8018050582321b801 +8023211bb003254523212321591b2159442db800132c4b535845441b2121592db800142c4bb8 +00095058b101018e59b801ff85b800441db9000900035f5e2db800152c2020456944b001602d +b800162cb800152a212db800172c2046b003254652582359208a208a49648a204620686164b0 +04254620686164525823658a592f20b00053586920b000545821b040591b6920b000545821b0 +406559593a2db800182c2046b00425465258238a592046206a6164b0042546206a6164525823 +8a592ffd2db800192c4b20b0032650585158b080441bb04044591b21212045b0c05058b0c044 +1b2159592db8001a2c2020456944b001602020457d691844b001602db8001b2cb8001a2a2db8 +001c2c4b20b003265358b0401bb000598a8a20b0032653582321b0808a8a1b8a235920b00326 +53582321b800c08a8a1b8a235920b0032653582321b801008a8a1b8a235920b0032653582321 +b801408a8a1b8a235920b80003265358b0032545b8018050582321b8018023211bb003254523 +212321591b2159442db8001d2c4b535845441b2121592d0000000001000000010000d0ec3e26 +5f0f3cf5011903e800000000b643f71100000000dee02d13fe4ffea104e5046b000000090002 +0001000000000001000003a3ff2b001b0534fe4fff3404e50001000000000000000000000000 +0000000201f400320116000000000000000000380000003800010000000200880007006d0007 +000200000000001e00000200043900040001b800142b01ba0005001000162b01bf0013011300 +db00af007d00450000001c2bbf001400fa00db0092006800450000001c2b00bf000f011300db +00af007d00450000001c2bbf001000cc00a70092006800450000001c2bbf0011006e005a0046 +0032001e0000001c2bbf001200300027001f0016000d0000001c2b00ba00150004001b2bb800 +0e20457d691844b8000a2b01ba00020002000c2b01bf0003011300e100af007d004b00000012 +2b00bf0002011300e100af007d004b000000122b00ba0004000500112bb8000120457d691844 +b800002b000000> +] def +/f-1-0 currentdict end definefont pop +%%EndResource +%%BeginResource: font STIXTwoText +11 dict begin +/FontType 42 def +/FontName /STIXTwoText def +/PaintType 0 def +/FontMatrix [ 1 0 0 1 0 0 ] def +/FontBBox [ 0 0 0 0 ] def +/Encoding 256 array def +0 1 255 { Encoding exch /.notdef put } for +Encoding 32 /space put +Encoding 46 /period put +Encoding 49 /one put +Encoding 56 /eight put +Encoding 57 /nine put +Encoding 67 /C put +Encoding 77 /M put +Encoding 84 /T put +Encoding 97 /a put +Encoding 104 /h put +Encoding 105 /i put +Encoding 109 /m put +Encoding 111 /o put +Encoding 116 /t put +Encoding 121 /y put +/CharStrings 16 dict dup begin +/.notdef 0 def +/T 1 def +/i 2 def +/m 3 def +/o 4 def +/t 5 def +/h 6 def +/y 7 def +/space 8 def +/C 9 def +/period 10 def +/M 11 def +/a 12 def +/one 13 def +/nine 14 def +/eight 15 def +end readonly def +/sfnts [ +<000100000007004000020030676c79668b9ad17e0000007c0000073868656164193c7cc10000 +07b400000036686865610554023d000007ec00000024686d7478203501fb0000081000000040 +6c6f636100003e3000000850000000446d6178700027012e0000089400000020707265706806 +8c85000008b4000000070004000aff57025303110003000f0013003800000521112101222635 +343633321615140601112111032335343e033534262322061514161615140623223534363332 +161615140e03150253fdb70249feda1d1d1f1c1a1e1efef501e2df281622211638302c2a0a0b +1b12335e4c315434212f3021a903bafce71f1918232417182002e6fcae0352fdcc1a273c3437 +452e3b371f17101213131715463d4d1f42342c4a403b3c2100000001000f0000024b0291001b +00002121353236363511232206060723372117232e022323111416163301bffede2a2a0e4037 +37180b1f0b0229081f0b1836383f0e2a2b1e0d2b2d01e1163a37b4b4373a16fe1f2d2b0d0000 +000200200000010102a100150021000021233532363635113426232206313537331114161633 +0322263534363332161514060101e1221d0716160a0f7e1a081f217019201f1a1a1f1f1c0d20 +1c0117200f021d1cfe831d200c0214221717212117172200000300200000033d01e5001e0036 +0052000021233532363635353426232206060727333636333216171616171114161633052335 +3236363511342623220631353733151711141616330523353236363535342626232206072733 +36363332161515141616330226ed2420092d231c31280e080f294c332d370e020201092024fe +dee4201d0915150b107d18030c201f0239e2221e0717271821401a0b0f294e283b46071f221d +0e2623c6402b18200e3223313427030704fef822260f1d1d0b1f1e01181b12021d1d5c16fef1 +1c1d0b1d1d12271ec02e30132f1632292a4a5bcc1f27110000020022fff601e001e5000d001a +0000052226353436363332161514060627323636353426232206151416010269773865436777 +39643d29381d43433946470a8379496d3d806f54723a28265c515c726060776b00010025fff6 +013802620019000025170e022322263511233536363733153315231114163332360125131321 +2820322e3723331b197171131d181b5a101b25143b43013617164b408e2afee6352a14000002 +00160000022c02c2001c003100002123353236363535342626232206073733363633321e0215 +15141633052335323635113426232206313537331114161633022ce6231e080c27291f402901 +0e2f4b282b351c0a1b2ffed5e3271f1d140c11861b0820221d0e1e18ad2945292128372c2622 +37411fc728201d1d162a02001a0e021c23fd9f1a1e0c00000001fff4ff1501ed01d900320000 +17222635343633321633323e02353426270326262335331522061514161f0233133636353426 +23353315220607030e024d1f281b131a290a0e201f13150993071a1bd622170a04620d076102 +031f19aa1e1c0b9c1d3740eb181c1714162b3c350b0a3414014111131d1e0d0d0a170bdc3101 +22050f050f0a1d1d1b1dfe664c5e2b0000010032fff50278029d002300000522262635343636 +333216163332363733152326262322061514161633323637170e02016c678c47549460354026 +0c0c0d091e2210674d6c753d6c4645682a181b4b640b589a616d98501212150fe562589a8664 +7e3c332e15283f2400000001003efff800b70072000b0000172226353436333216151406791e +1d201c1d20200822191a25261a1723000001001c000003520291002d00002123353236363511 +3426262335331333133315220606151114161633152135323636351123032303231114161633 +0107eb29280e0e2728ccd304d2be23260e0e2624fef627260c04e918ec040e27261e0f323301 +8526270f1efe0901f71e0f2725fe5f24270e1e1e0e272401affdda0225fe6d33320f00010026 +fff901dc01e5003c000017222635343e03373534262322061514062322263534363633321615 +151416333236371706062322262727350e021514163332363717230e029d3a3d253d47441a2d +2d2b1817150f1b2b4f3652440e100e170a0f192d26231505062d503228201a391b080c172b31 +0740302837261a12082c4137242d171717191c32204c4ee31f120e0b10242128250cad0b1e30 +27252c1a18241420110000000001004a000001aa027f00140000212135323635113426232206 +06073537331114163301aafea6473a0e130a242810c21d3c451c1e2501a71a170407052137fd +e0251e0000020027fff301c2028600170024000017273e023727060623222635343633321616 +15140e0213323635342626232206151416550245744d0b06223b2652626b5e4b5c2b34608651 +2c4319372c313d3d0d1d08417151011f1f6f6365714a7c4a61906130012535403f60374e6046 +57000001002efff401c002870040000017222626353436363735170e02151416333236363534 +262627272e02353436363332161615140606071527363635342623220615141617171e021514 +0606f63a5a341e3d2e271f2c1745391f341f1b474205383b15315637324f2e1a382f2a382937 +30333b4249073f481e335b0c2245332837301f0c15192c34244340172d2221363b2a02263a39 +232e4224243e2824342b1a0c162043323235332e2e422c05253f402a34492500000000010000 +00022148619f42b15f0f3cf5000203e800000000dbffc65b00000000dcc85198fc4cfe8b0511 +04170000000600020001000000000001000002faff1200fa053efc4cfddc0511000100000000 +000000000000000000000010025d000a025b000f011d00200354002002020022013b00250241 +001601e3fff400eb0000029e003200f5003e037f001c01e0002601ef004a01ef002701ef002e +00000000000000a80000010000000164000002480000029c000002ec00000378000004080000 +040800000474000004a000000524000005cc0000061000000680000007380001000000100088 +000c00a40006000100000000000000000000000000040001b801ff85b0048d0000> +] def +/f-2-0 currentdict end definefont pop +%%EndResource +%%EndSetup +%%Page: 1 1 +%%BeginPageSetup +%%PageMedia: 200x200mm +%%PageBoundingBox: 77 121 490 446 +567 567 cairo_set_page_size +%%EndPageSetup +q 77 121 413 325 rectclip +1 0 0 -1 0 567 cm q +0.129412 g +BT +11.99999 0 0 -11.99999 77.628673 239.929353 Tm +/f-0-0 1 Tf +[(A spect)5(er is haunting the modern w)5(orld, the spect)5(er of)-50( cr\ +ypt)5(o anar)10(ch)20(y)75(.)]TJ +0 -2.603621 Td +[(Comput)5(er t)5(echnology is on the v)5(erg)-5(e of)-50( pr)10(oviding \ +the ability for individuals and)]TJ +/f-1-0 1 Tf +( )Tj +/f-0-0 1 Tf +0 -1.301811 Td +[(gr)10(oups t)5(o communicat)5(e and int)5(er)15(act with each other in \ +a t)5(otally anon)20(ymous)]TJ +/f-1-0 1 Tf +( )Tj +/f-0-0 1 Tf +0 -1.301811 Td +[(manner)65(. )20(T)50(w)5(o persons ma)20(y e)10(x)10(chang)-5(e messag) +-5(es, conduct business, and neg)-5(otiat)5(e)]TJ +/f-1-0 1 Tf +( )Tj +/f-0-0 1 Tf +0 -1.301811 Td +[(electr)10(onic contr)15(acts without ev)5(er knowing the )20(T)30(rue N\ +)10(ame, or leg)10(al identity)75(, of)-50( the)]TJ +/f-1-0 1 Tf +( )Tj +/f-0-0 1 Tf +0 -1.301811 Td +[(other)65(. Int)5(er)15(actions ov)5(er netw)5(orks will be untr)15(acea\ +ble, via e)10(xt)5(ensiv)5(e r)10(e)-15(-r)10(outing of)]TJ +/f-1-0 1 Tf +( )Tj +/f-0-0 1 Tf +0 -1.301811 Td +[(encrypt)5(ed pack)25(ets and tamper)25(-pr)10(oof)-50( bo)10(x)10(es wh\ +ich implement crypt)5(ogr)15(aphic)]TJ +/f-1-0 1 Tf +( )Tj +/f-0-0 1 Tf +0 -1.301812 Td +[(pr)10(ot)5(ocols with nearly perfect assur)15(ance ag)10(ainst an)20(y \ +tampering)10(. R)15(eputations will)]TJ +/f-1-0 1 Tf +( )Tj +/f-0-0 1 Tf +0 -1.301812 Td +[(be of)-50( centr)15(al importance, far mor)10(e important in dealings t\ +han ev)5(en the cr)10(edit)]TJ +/f-1-0 1 Tf +( )Tj +/f-0-0 1 Tf +0 -1.301812 Td +[(r)15(atings of)-50( t)5(oda)20(y)75(. )20(These dev)5(elopments will al\ +t)5(er complet)5(ely the natur)10(e of)]TJ +/f-1-0 1 Tf +( )Tj +/f-0-0 1 Tf +0 -1.301812 Td +[(g)-5(ov)5(ernment r)10(egulation, the ability t)5(o tax and contr)10(ol\ + economic int)5(er)15(actions, the)]TJ +/f-1-0 1 Tf +( )Tj +/f-0-0 1 Tf +0 -1.301812 Td +[(ability t)5(o k)25(eep information secr)10(et, and will ev)5(en alt)5 +(er the natur)10(e of)-50( trust and)]TJ +/f-1-0 1 Tf +( )Tj +/f-0-0 1 Tf +0 -1.301812 Td +[(r)10(eputation.)]TJ +26.999999 0 0 -26.999999 99.702516 140.528356 Tm +[(The Crypt)5(o Anar)10(chist Manifest)5(o)]TJ +15.000009 0 0 -15.000009 227.613527 178.634351 Tm +/f-2-0 1 Tf +[(Timoth)20(y C. Ma)20(y)]TJ +ET +0.477647 g +BT +15.000009 0 0 -15.000009 268.871033 212.384351 Tm +/f-2-0 1 Tf +(1988)Tj +ET +0.129412 g +BT +15.000009 0 0 -15.000009 281.958562 231.134358 Tm +/f-2-0 1 Tf +( )Tj +ET +Q Q +showpage +%%Trailer +%%EOF diff --git a/2024/may.ps b/2024/may.ps new file mode 100644 index 0000000..2999fe5 --- /dev/null +++ b/2024/may.ps @@ -0,0 +1,35 @@ +%!PS + +/fontFace /Times-Roman def + +/fontSize 16 def + +/marginSize 24 def + +/rows [ + [0.3 0.3 0.3] + 36 + ( The Crypto Anarchist Manifesto) + 22 + () + ( Timothy C. May) + () + [0.8 0.8 0.8] + ( 1988) + () + 16 + [0.3 0.3 0.3] + (A specter is haunting the modern world, the specter of crypto anarchy.) + () + (Computer technology is on the verge of providing the ability for individuals and) + (groups to communicate and interact with each other in a totally anonymous manner.) + (Two persons may exchange messages, conduct business, and negotiate electronic) + (contracts without ever knowing the True Name, or legal identity, of the other.) + (Interactions over networks will be untraceable, via extensive re-routing of encrypted) + (packets and tamper-proof boxes which implement cryptographic protocols with nearly) + (perfect assurance against any tampering. Reputations will be of central importance, far) + (more important in dealings than even the credit ratings of today. These developments) + (will alter completely the nature of government regulation, the ability to tax and control) + (economic interactions, the ability to keep information secret, and will even alter the) + (nature of trust and reputation.) +] def diff --git a/2024/may.svg b/2024/may.svg new file mode 100644 index 0000000..6b68487 --- /dev/null +++ b/2024/may.svg @@ -0,0 +1,225 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<!-- Created with Inkscape (http://www.inkscape.org/) --> + +<svg + width="200mm" + height="200mm" + viewBox="0 0 200 200" + version="1.1" + id="svg1" + xml:space="preserve" + inkscape:version="1.4 (e7c3feb1, 2024-10-09)" + sodipodi:docname="may.svg" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns="http://www.w3.org/2000/svg" + xmlns:svg="http://www.w3.org/2000/svg"><sodipodi:namedview + id="namedview1" + pagecolor="#ffffff" + bordercolor="#000000" + borderopacity="0.25" + inkscape:showpageshadow="2" + inkscape:pageopacity="0.0" + inkscape:pagecheckerboard="0" + inkscape:deskcolor="#d1d1d1" + inkscape:document-units="mm" + inkscape:zoom="0.27060195" + inkscape:cx="9.2386622" + inkscape:cy="545.08107" + inkscape:window-width="1472" + inkscape:window-height="896" + inkscape:window-x="0" + inkscape:window-y="32" + inkscape:window-maximized="0" + inkscape:current-layer="layer1" /><defs + id="defs1" /><g + inkscape:label="Layer 1" + inkscape:groupmode="layer" + id="layer1" + transform="translate(-29.169659,-84.71086)"><g + id="g32" + transform="translate(27.398371,42.783957)"><text + xml:space="preserve" + style="font-style:normal;font-variant:normal;font-weight:100;font-stretch:normal;font-size:4.23333px;font-family:'Helvetica Neue';-inkscape-font-specification:'Helvetica Neue, Thin';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;text-align:center;writing-mode:lr-tb;direction:ltr;text-anchor:middle;white-space:pre;inline-size:146.432;display:inline;fill:#1a1a1a;stroke-width:2.82223;stroke-linecap:round;stroke-linejoin:round" + x="-387.17783" + y="79.068176" + id="text1-9" + transform="translate(489.55149,36.478482)"><tspan + x="-387.17783" + y="79.068176" + id="tspan5"><tspan + style="font-weight:normal;font-family:'STIX Two Text';-inkscape-font-specification:'STIX Two Text, Normal';text-align:start;text-anchor:start;fill:#212121" + id="tspan3"> +</tspan></tspan><tspan + x="-387.17783" + y="84.579171" + id="tspan10"><tspan + style="font-weight:normal;font-family:'STIX Two Text';-inkscape-font-specification:'STIX Two Text, Normal';text-align:start;text-anchor:start;fill:#212121" + id="tspan6"> +</tspan></tspan><tspan + x="-387.17783" + y="90.090165" + id="tspan12"><tspan + style="font-weight:normal;font-family:'STIX Two Text';-inkscape-font-specification:'STIX Two Text, Normal';text-align:start;text-anchor:start;fill:#212121" + id="tspan11">A specter is haunting the modern world, the specter of crypto anarchy. +</tspan></tspan><tspan + x="-387.17783" + y="95.601159" + id="tspan14"><tspan + style="font-weight:normal;font-family:'STIX Two Text';-inkscape-font-specification:'STIX Two Text, Normal';text-align:start;text-anchor:start;fill:#212121" + id="tspan13"> +</tspan></tspan><tspan + x="-387.17783" + y="101.11215" + id="tspan17"><tspan + style="font-weight:normal;font-family:'STIX Two Text';-inkscape-font-specification:'STIX Two Text, Normal';text-align:start;text-anchor:start;fill:#212121" + id="tspan15">Computer technology is on the verge of providing the ability for individuals and</tspan><tspan + style="fill:#212121" + id="tspan16"></tspan><tspan + y="101.11215" + id="tspan18"> </tspan></tspan><tspan + x="-387.17783" + y="106.62315" + id="tspan21"><tspan + style="font-weight:normal;font-family:'STIX Two Text';-inkscape-font-specification:'STIX Two Text, Normal';text-align:start;text-anchor:start;fill:#212121" + id="tspan19">groups to communicate and interact with each other in a totally anonymous</tspan><tspan + style="fill:#212121" + id="tspan20"></tspan><tspan + y="106.62315" + id="tspan24"> </tspan></tspan><tspan + x="-387.17783" + y="112.13414" + id="tspan29"><tspan + style="font-weight:normal;font-family:'STIX Two Text';-inkscape-font-specification:'STIX Two Text, Normal';text-align:start;text-anchor:start;fill:#212121" + id="tspan25">manner. Two persons may exchange messages, conduct business, and negotiate</tspan><tspan + style="fill:#212121" + id="tspan26"></tspan><tspan + y="112.13414" + id="tspan35"> </tspan></tspan><tspan + x="-387.17783" + y="117.64513" + id="tspan44"><tspan + style="font-weight:normal;font-family:'STIX Two Text';-inkscape-font-specification:'STIX Two Text, Normal';text-align:start;text-anchor:start;fill:#212121" + id="tspan38">electronic contracts without ever knowing the True Name, or legal identity, of the</tspan><tspan + style="fill:#212121" + id="tspan41"></tspan><tspan + y="117.64513" + id="tspan47"> </tspan></tspan><tspan + x="-387.17783" + y="123.15613" + id="tspan56"><tspan + style="font-weight:normal;font-family:'STIX Two Text';-inkscape-font-specification:'STIX Two Text, Normal';text-align:start;text-anchor:start;fill:#212121" + id="tspan50">other. Interactions over networks will be untraceable, via extensive re-routing of</tspan><tspan + style="fill:#212121" + id="tspan53"></tspan><tspan + y="123.15613" + id="tspan57"> </tspan></tspan><tspan + x="-387.17783" + y="128.66712" + id="tspan60"><tspan + style="font-weight:normal;font-family:'STIX Two Text';-inkscape-font-specification:'STIX Two Text, Normal';text-align:start;text-anchor:start;fill:#212121" + id="tspan58">encrypted packets and tamper-proof boxes which implement cryptographic</tspan><tspan + style="fill:#212121" + id="tspan59"></tspan><tspan + y="128.66712" + id="tspan61"> </tspan></tspan><tspan + x="-387.17783" + y="134.17812" + id="tspan64"><tspan + style="font-weight:normal;font-family:'STIX Two Text';-inkscape-font-specification:'STIX Two Text, Normal';text-align:start;text-anchor:start;fill:#212121" + id="tspan62">protocols with nearly perfect assurance against any tampering. Reputations will</tspan><tspan + style="fill:#212121" + id="tspan63"></tspan><tspan + y="134.17812" + id="tspan65"> </tspan></tspan><tspan + x="-387.17783" + y="139.68913" + id="tspan68"><tspan + style="font-weight:normal;font-family:'STIX Two Text';-inkscape-font-specification:'STIX Two Text, Normal';text-align:start;text-anchor:start;fill:#212121" + id="tspan66">be of central importance, far more important in dealings than even the credit</tspan><tspan + style="fill:#212121" + id="tspan67"></tspan><tspan + y="139.68913" + id="tspan69"> </tspan></tspan><tspan + x="-387.17783" + y="145.20013" + id="tspan72"><tspan + style="font-weight:normal;font-family:'STIX Two Text';-inkscape-font-specification:'STIX Two Text, Normal';text-align:start;text-anchor:start;fill:#212121" + id="tspan70">ratings of today. These developments will alter completely the nature of</tspan><tspan + style="fill:#212121" + id="tspan71"></tspan><tspan + y="145.20013" + id="tspan73"> </tspan></tspan><tspan + x="-387.17783" + y="150.71113" + id="tspan76"><tspan + style="font-weight:normal;font-family:'STIX Two Text';-inkscape-font-specification:'STIX Two Text, Normal';text-align:start;text-anchor:start;fill:#212121" + id="tspan74">government regulation, the ability to tax and control economic interactions, the</tspan><tspan + style="fill:#212121" + id="tspan75"></tspan><tspan + y="150.71113" + id="tspan77"> </tspan></tspan><tspan + x="-387.17783" + y="156.22213" + id="tspan80"><tspan + style="font-weight:normal;font-family:'STIX Two Text';-inkscape-font-specification:'STIX Two Text, Normal';text-align:start;text-anchor:start;fill:#212121" + id="tspan78">ability to keep information secret, and will even alter the nature of trust and</tspan><tspan + style="fill:#212121" + id="tspan79"></tspan><tspan + y="156.22213" + id="tspan81"> </tspan></tspan><tspan + x="-387.17783" + y="161.73313" + id="tspan83"><tspan + style="font-weight:normal;font-family:'STIX Two Text';-inkscape-font-specification:'STIX Two Text, Normal';text-align:start;text-anchor:start;fill:#212121" + id="tspan82">reputation.</tspan></tspan></text><text + xml:space="preserve" + style="font-style:normal;font-variant:normal;font-weight:100;font-stretch:normal;font-size:4.23333px;font-family:'Helvetica Neue';-inkscape-font-specification:'Helvetica Neue, Thin';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;text-align:center;writing-mode:lr-tb;direction:ltr;text-anchor:middle;white-space:pre;inline-size:146.432;display:inline;fill:#1a1a1a;stroke-width:2.82223;stroke-linecap:round;stroke-linejoin:round" + x="-387.17783" + y="79.068176" + id="text1-0" + transform="translate(489.03951,12.434008)"><tspan + x="-387.17783" + y="79.068176" + id="tspan86"><tspan + style="font-weight:normal;font-size:9.525px;font-family:'STIX Two Text';-inkscape-font-specification:'STIX Two Text, Normal';fill:#212121" + id="tspan84">The Crypto Anarchist Manifesto</tspan><tspan + style="fill:#212121" + id="tspan85"> +</tspan></tspan><tspan + x="-387.17783" + y="86.500047" + id="tspan88"><tspan + style="fill:#212121" + id="tspan87"> +</tspan></tspan><tspan + x="-387.17783" + y="92.511124" + id="tspan91"><tspan + style="font-weight:normal;font-size:5.29167px;font-family:'STIX Two Text';-inkscape-font-specification:'STIX Two Text, @wght=700';font-variation-settings:'wght' 700;fill:#212121" + id="tspan89">Timothy C. May</tspan><tspan + style="fill:#212121" + id="tspan90"> +</tspan></tspan><tspan + x="-387.17783" + y="98.406297" + id="tspan93"><tspan + style="fill:#212121" + id="tspan92"> +</tspan></tspan><tspan + x="-387.17783" + y="104.41737" + id="tspan96"><tspan + style="fill:#212121;fill-opacity:0.6" + id="tspan94">1988</tspan><tspan + style="font-weight:normal;font-size:5.29167px;font-family:'STIX Two Text';-inkscape-font-specification:'STIX Two Text, @wght=700';font-variation-settings:'wght' 700;fill:#212121" + id="tspan95"> +</tspan></tspan><tspan + x="-387.17783" + y="111.03196" + id="tspan99"><tspan + style="font-weight:normal;font-size:5.29167px;font-family:'STIX Two Text';-inkscape-font-specification:'STIX Two Text, @wght=700';font-variation-settings:'wght' 700;fill:#212121" + id="tspan97"> </tspan><tspan + style="font-weight:normal;font-family:'STIX Two Text';-inkscape-font-specification:'STIX Two Text, Normal';text-align:start;text-anchor:start;fill:#212121" + id="tspan98"> +</tspan></tspan></text></g></g></svg> diff --git a/2024/row-by-row-left-to-right.ps b/2024/row-by-row-left-to-right.ps new file mode 100644 index 0000000..e0d22b2 --- /dev/null +++ b/2024/row-by-row-left-to-right.ps @@ -0,0 +1,33 @@ +%!PS + + +/pagewidth currentpagedevice /PageSize get 0 get def +/pageheight currentpagedevice /PageSize get 1 get def + +/centre fontSize 2 div neg def +/offset pageheight marginSize sub def + +rows { + dup type /stringtype eq { + gsave + marginSize offset translate + 0 centre moveto + show + grestore + /offset offset fontSize sub def + } { + dup type /arraytype eq { + aload pop setgray pop pop + } { + /fontSize exch def + /vcentre fontSize 2 div neg def + fontFace findfont + fontSize scalefont + setfont + } ifelse + } ifelse + + +} forall + +showpage
rheaplex/postscript-viruses
fd7128f3f5d7436224732d21f1661a7d14dce54e
Add second commission.
diff --git a/2024/Makefile b/2024/Makefile new file mode 100644 index 0000000..723cea1 --- /dev/null +++ b/2024/Makefile @@ -0,0 +1,19 @@ +abstract-1.pdf: abstract-1.ps + gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER \ + -dDEVICEWIDTHPOINTS=1250 -dDEVICEHEIGHTPOINTS=504 \ + -dPDFFitPage -sOutputFile=abstract-1.pdf \ + ../2023/payload.ps abstract-1.ps + +abstract-2.pdf: abstract-2.ps + gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER \ + -dDEVICEWIDTHPOINTS=1284 -dDEVICEHEIGHTPOINTS=530 \ + -dPDFFitPage -sOutputFile=abstract-2.pdf \ + ../2023/payload.ps abstract-2.ps + +abstract-3.pdf: abstract-3.ps + gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER \ + -dDEVICEWIDTHPOINTS=1308 -dDEVICEHEIGHTPOINTS=500 \ + -dPDFFitPage -sOutputFile=abstract-3.pdf \ + ../2023/payload.ps abstract-3.ps + +all: abstract-1.pdf abstract-2.pdf abstract-3.pdf diff --git a/2024/abstract-1.pdf b/2024/abstract-1.pdf new file mode 100644 index 0000000..c8f8b7f Binary files /dev/null and b/2024/abstract-1.pdf differ diff --git a/2024/abstract-1.ps b/2024/abstract-1.ps new file mode 100644 index 0000000..69bd376 --- /dev/null +++ b/2024/abstract-1.ps @@ -0,0 +1,39 @@ +%!PS + +/pagewidth currentpagedevice /PageSize get 0 get def +/pageheight currentpagedevice /PageSize get 1 get def + +/fontSize 36 def +/centre fontSize 2 div neg def +% number sub is arbitrary to centre on the page. +/offset pageheight 9 sub def + +/Times-Roman findfont +fontSize scalefont +setfont + +[ +(Abstract. A purely peer-to-peer version of electronic cash would allow online) +(payments to be sent directly from one party to another without going through a) +(financial institution. Digital signatures provide part of the solution, but the main) +(benefits are lost if a trusted third party is still required to prevent double-spending.) +(We propose a solution to the double-spending problem using a peer-to-peer network.) +(The network timestamps transactions by hashing them into an ongoing chain of) +(hash-based proof-of-work, forming a record that cannot be changed without redoing) +(the proof-of-work. The longest chain not only serves as proof of the sequence of) +(events witnessed, but proof that it came from the largest pool of CPU power. As) +(long as a majority of CPU power is controlled by nodes that are not cooperating to) +(attack the network, they'll generate the longest chain and outpace attackers. The) +(network itself requires minimal structure. Messages are broadcast on a best effort) +(basis, and nodes can leave and rejoin the network at will, accepting the longest) +(proof-of-work chain as proof of what happened while they were gone.) +] { + gsave + 0 offset translate + 0 centre moveto + show + grestore + /offset offset fontSize sub def +} forall + +showpage diff --git a/2024/abstract-2.pdf b/2024/abstract-2.pdf new file mode 100644 index 0000000..5a965f7 Binary files /dev/null and b/2024/abstract-2.pdf differ diff --git a/2024/abstract-2.ps b/2024/abstract-2.ps new file mode 100644 index 0000000..5bc2acd --- /dev/null +++ b/2024/abstract-2.ps @@ -0,0 +1,36 @@ +%!PS + +/pagewidth currentpagedevice /PageSize get 0 get def +/pageheight currentpagedevice /PageSize get 1 get def + +/fontSize 36 def +/centre fontSize 2 div neg def +% number sub is arbitrary to centre on the page. +/offset pageheight fontSize sub def + +/Times-Roman findfont +fontSize scalefont +setfont + +[ +(Abstract. A purely peer-to-peer version of electronic cash would allow online) +(payments to be sent directly from one party to another without going through a) +(financial institution. Digital signatures provide part of the solution, but the main) +(benefits are lost if a trusted third party is still required to prevent double-spending.) +(We propose a solution to the double-spending problem using a peer-to-peer network.) +(The network timestamps transactions by hashing them into an ongoing chain of) +(hash-based proof-of-work, forming a record that cannot be changed without redoing) +(the proof-of-work. The longest chain not only serves as proof of the sequence of) +(events witnessed, but proof that it came from the largest pool of CPU power. As) +(long as a majority of CPU power is controlled by nodes that are not cooperating to) +(attack the network, they'll generate the longest chain and outpace attackers. The) +(network itself requires minimal structure. Messages are broadcast on a best effort) +(basis, and nodes can leave and rejoin the network at will, accepting the longest) +(proof-of-work chain as proof of what happened while they were gone.) +] { + 0 offset moveto + show + /offset offset fontSize sub def +} forall + +showpage diff --git a/2024/abstract-3-final.pdf b/2024/abstract-3-final.pdf new file mode 100644 index 0000000..4a218a1 Binary files /dev/null and b/2024/abstract-3-final.pdf differ diff --git a/2024/abstract-3-final.png b/2024/abstract-3-final.png new file mode 100644 index 0000000..f162375 Binary files /dev/null and b/2024/abstract-3-final.png differ diff --git a/2024/abstract-3.pdf b/2024/abstract-3.pdf new file mode 100644 index 0000000..03bf3cb Binary files /dev/null and b/2024/abstract-3.pdf differ diff --git a/2024/abstract-3.ps b/2024/abstract-3.ps new file mode 100644 index 0000000..9f39166 --- /dev/null +++ b/2024/abstract-3.ps @@ -0,0 +1,41 @@ +%!PS + +/pagewidth currentpagedevice /PageSize get 0 get def +/pageheight currentpagedevice /PageSize get 1 get def + +/fontSize 36 def +/vcentre fontSize 2 div neg def +/hcentre pagewidth 2 div def +% number sub is arbitrary to centre on the page. +/voffset pageheight 6 sub def +/hoffset pagewidth 2 div 48 add def + +/Times-Roman findfont +fontSize scalefont +setfont + +[ +(Abstract. A purely peer-to-peer version of electronic cash would allow online) +(payments to be sent directly from one party to another without going through a) +(financial institution. Digital signatures provide part of the solution, but the main) +(benefits are lost if a trusted third party is still required to prevent double-spending.) +(We propose a solution to the double-spending problem using a peer-to-peer network.) +(The network timestamps transactions by hashing them into an ongoing chain of) +(hash-based proof-of-work, forming a record that cannot be changed without redoing) +(the proof-of-work. The longest chain not only serves as proof of the sequence of) +(events witnessed, but proof that it came from the largest pool of CPU power. As) +(long as a majority of CPU power is controlled by nodes that are not cooperating to) +(attack the network, they'll generate the longest chain and outpace attackers. The) +(network itself requires minimal structure. Messages are broadcast on a best effort) +(basis, and nodes can leave and rejoin the network at will, accepting the longest) +(proof-of-work chain as proof of what happened while they were gone.) +] { + gsave + hoffset voffset translate + hcentre neg vcentre moveto + show + grestore + /voffset voffset fontSize sub def +} forall + +showpage
rheaplex/postscript-viruses
e5b1ba836564063a650e67052b4c60af9fa9d852
Make multiple versions of each glitch, although each will be 1/10.
diff --git a/2023/infected/alphabet.ps.d/alphabet.ps-1.pdf b/2023/infected/alphabet.ps.d/alphabet.ps-1.pdf new file mode 100644 index 0000000..c5645d4 Binary files /dev/null and b/2023/infected/alphabet.ps.d/alphabet.ps-1.pdf differ diff --git a/2023/infected/alphabet.ps.d/alphabet.ps-10.pdf b/2023/infected/alphabet.ps.d/alphabet.ps-10.pdf new file mode 100644 index 0000000..a66fd55 Binary files /dev/null and b/2023/infected/alphabet.ps.d/alphabet.ps-10.pdf differ diff --git a/2023/infected/alphabet.ps.d/alphabet.ps-11.pdf b/2023/infected/alphabet.ps.d/alphabet.ps-11.pdf new file mode 100644 index 0000000..82623d5 Binary files /dev/null and b/2023/infected/alphabet.ps.d/alphabet.ps-11.pdf differ diff --git a/2023/infected/alphabet.ps.d/alphabet.ps-12.pdf b/2023/infected/alphabet.ps.d/alphabet.ps-12.pdf new file mode 100644 index 0000000..d3dc422 Binary files /dev/null and b/2023/infected/alphabet.ps.d/alphabet.ps-12.pdf differ diff --git a/2023/infected/alphabet.ps.d/alphabet.ps-13.pdf b/2023/infected/alphabet.ps.d/alphabet.ps-13.pdf new file mode 100644 index 0000000..4c0ff95 Binary files /dev/null and b/2023/infected/alphabet.ps.d/alphabet.ps-13.pdf differ diff --git a/2023/infected/alphabet.ps.d/alphabet.ps-14.pdf b/2023/infected/alphabet.ps.d/alphabet.ps-14.pdf new file mode 100644 index 0000000..4429a62 Binary files /dev/null and b/2023/infected/alphabet.ps.d/alphabet.ps-14.pdf differ diff --git a/2023/infected/alphabet.ps.d/alphabet.ps-15.pdf b/2023/infected/alphabet.ps.d/alphabet.ps-15.pdf new file mode 100644 index 0000000..c44fa49 Binary files /dev/null and b/2023/infected/alphabet.ps.d/alphabet.ps-15.pdf differ diff --git a/2023/infected/alphabet.ps.d/alphabet.ps-16.pdf b/2023/infected/alphabet.ps.d/alphabet.ps-16.pdf new file mode 100644 index 0000000..b479e92 Binary files /dev/null and b/2023/infected/alphabet.ps.d/alphabet.ps-16.pdf differ diff --git a/2023/infected/alphabet.ps.d/alphabet.ps-17.pdf b/2023/infected/alphabet.ps.d/alphabet.ps-17.pdf new file mode 100644 index 0000000..ef4f1ab Binary files /dev/null and b/2023/infected/alphabet.ps.d/alphabet.ps-17.pdf differ diff --git a/2023/infected/alphabet.ps.d/alphabet.ps-18.pdf b/2023/infected/alphabet.ps.d/alphabet.ps-18.pdf new file mode 100644 index 0000000..85c6982 Binary files /dev/null and b/2023/infected/alphabet.ps.d/alphabet.ps-18.pdf differ diff --git a/2023/infected/alphabet.ps.d/alphabet.ps-19.pdf b/2023/infected/alphabet.ps.d/alphabet.ps-19.pdf new file mode 100644 index 0000000..4b2a2c1 Binary files /dev/null and b/2023/infected/alphabet.ps.d/alphabet.ps-19.pdf differ diff --git a/2023/infected/alphabet.ps.d/alphabet.ps-2.pdf b/2023/infected/alphabet.ps.d/alphabet.ps-2.pdf new file mode 100644 index 0000000..95d2234 Binary files /dev/null and b/2023/infected/alphabet.ps.d/alphabet.ps-2.pdf differ diff --git a/2023/infected/alphabet.ps.d/alphabet.ps-20.pdf b/2023/infected/alphabet.ps.d/alphabet.ps-20.pdf new file mode 100644 index 0000000..bc326eb Binary files /dev/null and b/2023/infected/alphabet.ps.d/alphabet.ps-20.pdf differ diff --git a/2023/infected/alphabet.ps.d/alphabet.ps-3.pdf b/2023/infected/alphabet.ps.d/alphabet.ps-3.pdf new file mode 100644 index 0000000..6c33db3 Binary files /dev/null and b/2023/infected/alphabet.ps.d/alphabet.ps-3.pdf differ diff --git a/2023/infected/alphabet.ps.d/alphabet.ps-4.pdf b/2023/infected/alphabet.ps.d/alphabet.ps-4.pdf new file mode 100644 index 0000000..c9f8ae8 Binary files /dev/null and b/2023/infected/alphabet.ps.d/alphabet.ps-4.pdf differ diff --git a/2023/infected/alphabet.ps.d/alphabet.ps-5.pdf b/2023/infected/alphabet.ps.d/alphabet.ps-5.pdf new file mode 100644 index 0000000..b66e20e Binary files /dev/null and b/2023/infected/alphabet.ps.d/alphabet.ps-5.pdf differ diff --git a/2023/infected/alphabet.ps.d/alphabet.ps-6.pdf b/2023/infected/alphabet.ps.d/alphabet.ps-6.pdf new file mode 100644 index 0000000..d5a299e Binary files /dev/null and b/2023/infected/alphabet.ps.d/alphabet.ps-6.pdf differ diff --git a/2023/infected/alphabet.ps.d/alphabet.ps-7.pdf b/2023/infected/alphabet.ps.d/alphabet.ps-7.pdf new file mode 100644 index 0000000..2f668f6 Binary files /dev/null and b/2023/infected/alphabet.ps.d/alphabet.ps-7.pdf differ diff --git a/2023/infected/alphabet.ps.d/alphabet.ps-8.pdf b/2023/infected/alphabet.ps.d/alphabet.ps-8.pdf new file mode 100644 index 0000000..fcba5eb Binary files /dev/null and b/2023/infected/alphabet.ps.d/alphabet.ps-8.pdf differ diff --git a/2023/infected/alphabet.ps.d/alphabet.ps-9.pdf b/2023/infected/alphabet.ps.d/alphabet.ps-9.pdf new file mode 100644 index 0000000..9973bd7 Binary files /dev/null and b/2023/infected/alphabet.ps.d/alphabet.ps-9.pdf differ diff --git a/2023/infected/colorcir.ps.d/colorcir.ps-1.pdf b/2023/infected/colorcir.ps.d/colorcir.ps-1.pdf new file mode 100644 index 0000000..75486fc Binary files /dev/null and b/2023/infected/colorcir.ps.d/colorcir.ps-1.pdf differ diff --git a/2023/infected/colorcir.ps.d/colorcir.ps-10.pdf b/2023/infected/colorcir.ps.d/colorcir.ps-10.pdf new file mode 100644 index 0000000..e2bca35 Binary files /dev/null and b/2023/infected/colorcir.ps.d/colorcir.ps-10.pdf differ diff --git a/2023/infected/colorcir.ps.d/colorcir.ps-11.pdf b/2023/infected/colorcir.ps.d/colorcir.ps-11.pdf new file mode 100644 index 0000000..29bdf30 Binary files /dev/null and b/2023/infected/colorcir.ps.d/colorcir.ps-11.pdf differ diff --git a/2023/infected/colorcir.ps.d/colorcir.ps-12.pdf b/2023/infected/colorcir.ps.d/colorcir.ps-12.pdf new file mode 100644 index 0000000..2ede285 Binary files /dev/null and b/2023/infected/colorcir.ps.d/colorcir.ps-12.pdf differ diff --git a/2023/infected/colorcir.ps.d/colorcir.ps-13.pdf b/2023/infected/colorcir.ps.d/colorcir.ps-13.pdf new file mode 100644 index 0000000..30be057 Binary files /dev/null and b/2023/infected/colorcir.ps.d/colorcir.ps-13.pdf differ diff --git a/2023/infected/colorcir.ps.d/colorcir.ps-14.pdf b/2023/infected/colorcir.ps.d/colorcir.ps-14.pdf new file mode 100644 index 0000000..d382abe Binary files /dev/null and b/2023/infected/colorcir.ps.d/colorcir.ps-14.pdf differ diff --git a/2023/infected/colorcir.ps.d/colorcir.ps-15.pdf b/2023/infected/colorcir.ps.d/colorcir.ps-15.pdf new file mode 100644 index 0000000..ea50428 Binary files /dev/null and b/2023/infected/colorcir.ps.d/colorcir.ps-15.pdf differ diff --git a/2023/infected/colorcir.ps.d/colorcir.ps-16.pdf b/2023/infected/colorcir.ps.d/colorcir.ps-16.pdf new file mode 100644 index 0000000..fc10fbd Binary files /dev/null and b/2023/infected/colorcir.ps.d/colorcir.ps-16.pdf differ diff --git a/2023/infected/colorcir.ps.d/colorcir.ps-17.pdf b/2023/infected/colorcir.ps.d/colorcir.ps-17.pdf new file mode 100644 index 0000000..a3a02e4 Binary files /dev/null and b/2023/infected/colorcir.ps.d/colorcir.ps-17.pdf differ diff --git a/2023/infected/colorcir.ps.d/colorcir.ps-18.pdf b/2023/infected/colorcir.ps.d/colorcir.ps-18.pdf new file mode 100644 index 0000000..b9b0372 Binary files /dev/null and b/2023/infected/colorcir.ps.d/colorcir.ps-18.pdf differ diff --git a/2023/infected/colorcir.ps.d/colorcir.ps-19.pdf b/2023/infected/colorcir.ps.d/colorcir.ps-19.pdf new file mode 100644 index 0000000..9ca9a92 Binary files /dev/null and b/2023/infected/colorcir.ps.d/colorcir.ps-19.pdf differ diff --git a/2023/infected/colorcir.ps.d/colorcir.ps-2.pdf b/2023/infected/colorcir.ps.d/colorcir.ps-2.pdf new file mode 100644 index 0000000..bfbd28d Binary files /dev/null and b/2023/infected/colorcir.ps.d/colorcir.ps-2.pdf differ diff --git a/2023/infected/colorcir.ps.d/colorcir.ps-20.pdf b/2023/infected/colorcir.ps.d/colorcir.ps-20.pdf new file mode 100644 index 0000000..343d4e4 Binary files /dev/null and b/2023/infected/colorcir.ps.d/colorcir.ps-20.pdf differ diff --git a/2023/infected/colorcir.ps.d/colorcir.ps-3.pdf b/2023/infected/colorcir.ps.d/colorcir.ps-3.pdf new file mode 100644 index 0000000..b396c5d Binary files /dev/null and b/2023/infected/colorcir.ps.d/colorcir.ps-3.pdf differ diff --git a/2023/infected/colorcir.ps.d/colorcir.ps-4.pdf b/2023/infected/colorcir.ps.d/colorcir.ps-4.pdf new file mode 100644 index 0000000..3ab874f Binary files /dev/null and b/2023/infected/colorcir.ps.d/colorcir.ps-4.pdf differ diff --git a/2023/infected/colorcir.ps.d/colorcir.ps-5.pdf b/2023/infected/colorcir.ps.d/colorcir.ps-5.pdf new file mode 100644 index 0000000..a788fc9 Binary files /dev/null and b/2023/infected/colorcir.ps.d/colorcir.ps-5.pdf differ diff --git a/2023/infected/colorcir.ps.d/colorcir.ps-6.pdf b/2023/infected/colorcir.ps.d/colorcir.ps-6.pdf new file mode 100644 index 0000000..d60945b Binary files /dev/null and b/2023/infected/colorcir.ps.d/colorcir.ps-6.pdf differ diff --git a/2023/infected/colorcir.ps.d/colorcir.ps-7.pdf b/2023/infected/colorcir.ps.d/colorcir.ps-7.pdf new file mode 100644 index 0000000..ed62cfb Binary files /dev/null and b/2023/infected/colorcir.ps.d/colorcir.ps-7.pdf differ diff --git a/2023/infected/colorcir.ps.d/colorcir.ps-8.pdf b/2023/infected/colorcir.ps.d/colorcir.ps-8.pdf new file mode 100644 index 0000000..82ad708 Binary files /dev/null and b/2023/infected/colorcir.ps.d/colorcir.ps-8.pdf differ diff --git a/2023/infected/colorcir.ps.d/colorcir.ps-9.pdf b/2023/infected/colorcir.ps.d/colorcir.ps-9.pdf new file mode 100644 index 0000000..6488e4d Binary files /dev/null and b/2023/infected/colorcir.ps.d/colorcir.ps-9.pdf differ diff --git a/2023/infected/doretree.ps.d/doretree.ps-1.pdf b/2023/infected/doretree.ps.d/doretree.ps-1.pdf new file mode 100644 index 0000000..b740db4 Binary files /dev/null and b/2023/infected/doretree.ps.d/doretree.ps-1.pdf differ diff --git a/2023/infected/doretree.ps.d/doretree.ps-10.pdf b/2023/infected/doretree.ps.d/doretree.ps-10.pdf new file mode 100644 index 0000000..7bd9027 Binary files /dev/null and b/2023/infected/doretree.ps.d/doretree.ps-10.pdf differ diff --git a/2023/infected/doretree.ps.d/doretree.ps-11.pdf b/2023/infected/doretree.ps.d/doretree.ps-11.pdf new file mode 100644 index 0000000..33bbae5 Binary files /dev/null and b/2023/infected/doretree.ps.d/doretree.ps-11.pdf differ diff --git a/2023/infected/doretree.ps.d/doretree.ps-12.pdf b/2023/infected/doretree.ps.d/doretree.ps-12.pdf new file mode 100644 index 0000000..0294ad0 Binary files /dev/null and b/2023/infected/doretree.ps.d/doretree.ps-12.pdf differ diff --git a/2023/infected/doretree.ps.d/doretree.ps-13.pdf b/2023/infected/doretree.ps.d/doretree.ps-13.pdf new file mode 100644 index 0000000..0719f9b Binary files /dev/null and b/2023/infected/doretree.ps.d/doretree.ps-13.pdf differ diff --git a/2023/infected/doretree.ps.d/doretree.ps-14.pdf b/2023/infected/doretree.ps.d/doretree.ps-14.pdf new file mode 100644 index 0000000..570830d Binary files /dev/null and b/2023/infected/doretree.ps.d/doretree.ps-14.pdf differ diff --git a/2023/infected/doretree.ps.d/doretree.ps-15.pdf b/2023/infected/doretree.ps.d/doretree.ps-15.pdf new file mode 100644 index 0000000..7f3bd8e Binary files /dev/null and b/2023/infected/doretree.ps.d/doretree.ps-15.pdf differ diff --git a/2023/infected/doretree.ps.d/doretree.ps-16.pdf b/2023/infected/doretree.ps.d/doretree.ps-16.pdf new file mode 100644 index 0000000..4336ccf Binary files /dev/null and b/2023/infected/doretree.ps.d/doretree.ps-16.pdf differ diff --git a/2023/infected/doretree.ps.d/doretree.ps-17.pdf b/2023/infected/doretree.ps.d/doretree.ps-17.pdf new file mode 100644 index 0000000..6fc986e Binary files /dev/null and b/2023/infected/doretree.ps.d/doretree.ps-17.pdf differ diff --git a/2023/infected/doretree.ps.d/doretree.ps-18.pdf b/2023/infected/doretree.ps.d/doretree.ps-18.pdf new file mode 100644 index 0000000..a12698d Binary files /dev/null and b/2023/infected/doretree.ps.d/doretree.ps-18.pdf differ diff --git a/2023/infected/doretree.ps.d/doretree.ps-19.pdf b/2023/infected/doretree.ps.d/doretree.ps-19.pdf new file mode 100644 index 0000000..42daf5d Binary files /dev/null and b/2023/infected/doretree.ps.d/doretree.ps-19.pdf differ diff --git a/2023/infected/doretree.ps.d/doretree.ps-2.pdf b/2023/infected/doretree.ps.d/doretree.ps-2.pdf new file mode 100644 index 0000000..d9b344a Binary files /dev/null and b/2023/infected/doretree.ps.d/doretree.ps-2.pdf differ diff --git a/2023/infected/doretree.ps.d/doretree.ps-20.pdf b/2023/infected/doretree.ps.d/doretree.ps-20.pdf new file mode 100644 index 0000000..89fca25 Binary files /dev/null and b/2023/infected/doretree.ps.d/doretree.ps-20.pdf differ diff --git a/2023/infected/doretree.ps.d/doretree.ps-3.pdf b/2023/infected/doretree.ps.d/doretree.ps-3.pdf new file mode 100644 index 0000000..fd90cb4 Binary files /dev/null and b/2023/infected/doretree.ps.d/doretree.ps-3.pdf differ diff --git a/2023/infected/doretree.ps.d/doretree.ps-4.pdf b/2023/infected/doretree.ps.d/doretree.ps-4.pdf new file mode 100644 index 0000000..164c5cd Binary files /dev/null and b/2023/infected/doretree.ps.d/doretree.ps-4.pdf differ diff --git a/2023/infected/doretree.ps.d/doretree.ps-5.pdf b/2023/infected/doretree.ps.d/doretree.ps-5.pdf new file mode 100644 index 0000000..7144502 Binary files /dev/null and b/2023/infected/doretree.ps.d/doretree.ps-5.pdf differ diff --git a/2023/infected/doretree.ps.d/doretree.ps-6.pdf b/2023/infected/doretree.ps.d/doretree.ps-6.pdf new file mode 100644 index 0000000..e347bd2 Binary files /dev/null and b/2023/infected/doretree.ps.d/doretree.ps-6.pdf differ diff --git a/2023/infected/doretree.ps.d/doretree.ps-7.pdf b/2023/infected/doretree.ps.d/doretree.ps-7.pdf new file mode 100644 index 0000000..767bdef Binary files /dev/null and b/2023/infected/doretree.ps.d/doretree.ps-7.pdf differ diff --git a/2023/infected/doretree.ps.d/doretree.ps-8.pdf b/2023/infected/doretree.ps.d/doretree.ps-8.pdf new file mode 100644 index 0000000..3b80ab6 Binary files /dev/null and b/2023/infected/doretree.ps.d/doretree.ps-8.pdf differ diff --git a/2023/infected/doretree.ps.d/doretree.ps-9.pdf b/2023/infected/doretree.ps.d/doretree.ps-9.pdf new file mode 100644 index 0000000..cf25816 Binary files /dev/null and b/2023/infected/doretree.ps.d/doretree.ps-9.pdf differ diff --git a/2023/infected/escher.ps.d/escher.ps-1.pdf b/2023/infected/escher.ps.d/escher.ps-1.pdf new file mode 100644 index 0000000..20fd767 Binary files /dev/null and b/2023/infected/escher.ps.d/escher.ps-1.pdf differ diff --git a/2023/infected/escher.ps.d/escher.ps-10.pdf b/2023/infected/escher.ps.d/escher.ps-10.pdf new file mode 100644 index 0000000..99c05b0 Binary files /dev/null and b/2023/infected/escher.ps.d/escher.ps-10.pdf differ diff --git a/2023/infected/escher.ps.d/escher.ps-11.pdf b/2023/infected/escher.ps.d/escher.ps-11.pdf new file mode 100644 index 0000000..0022634 Binary files /dev/null and b/2023/infected/escher.ps.d/escher.ps-11.pdf differ diff --git a/2023/infected/escher.ps.d/escher.ps-12.pdf b/2023/infected/escher.ps.d/escher.ps-12.pdf new file mode 100644 index 0000000..2f52afa Binary files /dev/null and b/2023/infected/escher.ps.d/escher.ps-12.pdf differ diff --git a/2023/infected/escher.ps.d/escher.ps-13.pdf b/2023/infected/escher.ps.d/escher.ps-13.pdf new file mode 100644 index 0000000..feb3484 Binary files /dev/null and b/2023/infected/escher.ps.d/escher.ps-13.pdf differ diff --git a/2023/infected/escher.ps.d/escher.ps-14.pdf b/2023/infected/escher.ps.d/escher.ps-14.pdf new file mode 100644 index 0000000..c7d1876 Binary files /dev/null and b/2023/infected/escher.ps.d/escher.ps-14.pdf differ diff --git a/2023/infected/escher.ps.d/escher.ps-15.pdf b/2023/infected/escher.ps.d/escher.ps-15.pdf new file mode 100644 index 0000000..087f641 Binary files /dev/null and b/2023/infected/escher.ps.d/escher.ps-15.pdf differ diff --git a/2023/infected/escher.ps.d/escher.ps-16.pdf b/2023/infected/escher.ps.d/escher.ps-16.pdf new file mode 100644 index 0000000..3c4b303 Binary files /dev/null and b/2023/infected/escher.ps.d/escher.ps-16.pdf differ diff --git a/2023/infected/escher.ps.d/escher.ps-17.pdf b/2023/infected/escher.ps.d/escher.ps-17.pdf new file mode 100644 index 0000000..c0944a7 Binary files /dev/null and b/2023/infected/escher.ps.d/escher.ps-17.pdf differ diff --git a/2023/infected/escher.ps.d/escher.ps-18.pdf b/2023/infected/escher.ps.d/escher.ps-18.pdf new file mode 100644 index 0000000..ed91faf Binary files /dev/null and b/2023/infected/escher.ps.d/escher.ps-18.pdf differ diff --git a/2023/infected/escher.ps.d/escher.ps-19.pdf b/2023/infected/escher.ps.d/escher.ps-19.pdf new file mode 100644 index 0000000..18ad18b Binary files /dev/null and b/2023/infected/escher.ps.d/escher.ps-19.pdf differ diff --git a/2023/infected/escher.ps.d/escher.ps-2.pdf b/2023/infected/escher.ps.d/escher.ps-2.pdf new file mode 100644 index 0000000..6573ab1 Binary files /dev/null and b/2023/infected/escher.ps.d/escher.ps-2.pdf differ diff --git a/2023/infected/escher.ps.d/escher.ps-20.pdf b/2023/infected/escher.ps.d/escher.ps-20.pdf new file mode 100644 index 0000000..0f3ef9a Binary files /dev/null and b/2023/infected/escher.ps.d/escher.ps-20.pdf differ diff --git a/2023/infected/escher.ps.d/escher.ps-3.pdf b/2023/infected/escher.ps.d/escher.ps-3.pdf new file mode 100644 index 0000000..620273f Binary files /dev/null and b/2023/infected/escher.ps.d/escher.ps-3.pdf differ diff --git a/2023/infected/escher.ps.d/escher.ps-4.pdf b/2023/infected/escher.ps.d/escher.ps-4.pdf new file mode 100644 index 0000000..9d1800b Binary files /dev/null and b/2023/infected/escher.ps.d/escher.ps-4.pdf differ diff --git a/2023/infected/escher.ps.d/escher.ps-5.pdf b/2023/infected/escher.ps.d/escher.ps-5.pdf new file mode 100644 index 0000000..b3d3ec3 Binary files /dev/null and b/2023/infected/escher.ps.d/escher.ps-5.pdf differ diff --git a/2023/infected/escher.ps.d/escher.ps-6.pdf b/2023/infected/escher.ps.d/escher.ps-6.pdf new file mode 100644 index 0000000..ea3bfaf Binary files /dev/null and b/2023/infected/escher.ps.d/escher.ps-6.pdf differ diff --git a/2023/infected/escher.ps.d/escher.ps-7.pdf b/2023/infected/escher.ps.d/escher.ps-7.pdf new file mode 100644 index 0000000..6fc39e1 Binary files /dev/null and b/2023/infected/escher.ps.d/escher.ps-7.pdf differ diff --git a/2023/infected/escher.ps.d/escher.ps-8.pdf b/2023/infected/escher.ps.d/escher.ps-8.pdf new file mode 100644 index 0000000..9cd51bc Binary files /dev/null and b/2023/infected/escher.ps.d/escher.ps-8.pdf differ diff --git a/2023/infected/escher.ps.d/escher.ps-9.pdf b/2023/infected/escher.ps.d/escher.ps-9.pdf new file mode 100644 index 0000000..013cd79 Binary files /dev/null and b/2023/infected/escher.ps.d/escher.ps-9.pdf differ diff --git a/2023/infected/golfer.eps.d/golfer.eps-1.pdf b/2023/infected/golfer.eps.d/golfer.eps-1.pdf new file mode 100644 index 0000000..d779258 Binary files /dev/null and b/2023/infected/golfer.eps.d/golfer.eps-1.pdf differ diff --git a/2023/infected/golfer.eps.d/golfer.eps-10.pdf b/2023/infected/golfer.eps.d/golfer.eps-10.pdf new file mode 100644 index 0000000..96e7539 Binary files /dev/null and b/2023/infected/golfer.eps.d/golfer.eps-10.pdf differ diff --git a/2023/infected/golfer.eps.d/golfer.eps-11.pdf b/2023/infected/golfer.eps.d/golfer.eps-11.pdf new file mode 100644 index 0000000..8df6ddd Binary files /dev/null and b/2023/infected/golfer.eps.d/golfer.eps-11.pdf differ diff --git a/2023/infected/golfer.eps.d/golfer.eps-12.pdf b/2023/infected/golfer.eps.d/golfer.eps-12.pdf new file mode 100644 index 0000000..a4ee97b Binary files /dev/null and b/2023/infected/golfer.eps.d/golfer.eps-12.pdf differ diff --git a/2023/infected/golfer.eps.d/golfer.eps-13.pdf b/2023/infected/golfer.eps.d/golfer.eps-13.pdf new file mode 100644 index 0000000..5134db4 Binary files /dev/null and b/2023/infected/golfer.eps.d/golfer.eps-13.pdf differ diff --git a/2023/infected/golfer.eps.d/golfer.eps-14.pdf b/2023/infected/golfer.eps.d/golfer.eps-14.pdf new file mode 100644 index 0000000..0a92507 Binary files /dev/null and b/2023/infected/golfer.eps.d/golfer.eps-14.pdf differ diff --git a/2023/infected/golfer.eps.d/golfer.eps-15.pdf b/2023/infected/golfer.eps.d/golfer.eps-15.pdf new file mode 100644 index 0000000..a9a907c Binary files /dev/null and b/2023/infected/golfer.eps.d/golfer.eps-15.pdf differ diff --git a/2023/infected/golfer.eps.d/golfer.eps-16.pdf b/2023/infected/golfer.eps.d/golfer.eps-16.pdf new file mode 100644 index 0000000..67ce0fd Binary files /dev/null and b/2023/infected/golfer.eps.d/golfer.eps-16.pdf differ diff --git a/2023/infected/golfer.eps.d/golfer.eps-17.pdf b/2023/infected/golfer.eps.d/golfer.eps-17.pdf new file mode 100644 index 0000000..2a95254 Binary files /dev/null and b/2023/infected/golfer.eps.d/golfer.eps-17.pdf differ diff --git a/2023/infected/golfer.eps.d/golfer.eps-18.pdf b/2023/infected/golfer.eps.d/golfer.eps-18.pdf new file mode 100644 index 0000000..ab55f12 Binary files /dev/null and b/2023/infected/golfer.eps.d/golfer.eps-18.pdf differ diff --git a/2023/infected/golfer.eps.d/golfer.eps-19.pdf b/2023/infected/golfer.eps.d/golfer.eps-19.pdf new file mode 100644 index 0000000..ab9d355 Binary files /dev/null and b/2023/infected/golfer.eps.d/golfer.eps-19.pdf differ diff --git a/2023/infected/golfer.eps.d/golfer.eps-2.pdf b/2023/infected/golfer.eps.d/golfer.eps-2.pdf new file mode 100644 index 0000000..4782285 Binary files /dev/null and b/2023/infected/golfer.eps.d/golfer.eps-2.pdf differ diff --git a/2023/infected/golfer.eps.d/golfer.eps-20.pdf b/2023/infected/golfer.eps.d/golfer.eps-20.pdf new file mode 100644 index 0000000..6474232 Binary files /dev/null and b/2023/infected/golfer.eps.d/golfer.eps-20.pdf differ diff --git a/2023/infected/golfer.eps.d/golfer.eps-3.pdf b/2023/infected/golfer.eps.d/golfer.eps-3.pdf new file mode 100644 index 0000000..5ab613d Binary files /dev/null and b/2023/infected/golfer.eps.d/golfer.eps-3.pdf differ diff --git a/2023/infected/golfer.eps.d/golfer.eps-4.pdf b/2023/infected/golfer.eps.d/golfer.eps-4.pdf new file mode 100644 index 0000000..e2e4440 Binary files /dev/null and b/2023/infected/golfer.eps.d/golfer.eps-4.pdf differ diff --git a/2023/infected/golfer.eps.d/golfer.eps-5.pdf b/2023/infected/golfer.eps.d/golfer.eps-5.pdf new file mode 100644 index 0000000..94f2c66 Binary files /dev/null and b/2023/infected/golfer.eps.d/golfer.eps-5.pdf differ diff --git a/2023/infected/golfer.eps.d/golfer.eps-6.pdf b/2023/infected/golfer.eps.d/golfer.eps-6.pdf new file mode 100644 index 0000000..18959b9 Binary files /dev/null and b/2023/infected/golfer.eps.d/golfer.eps-6.pdf differ diff --git a/2023/infected/golfer.eps.d/golfer.eps-7.pdf b/2023/infected/golfer.eps.d/golfer.eps-7.pdf new file mode 100644 index 0000000..c5bf46f Binary files /dev/null and b/2023/infected/golfer.eps.d/golfer.eps-7.pdf differ diff --git a/2023/infected/golfer.eps.d/golfer.eps-8.pdf b/2023/infected/golfer.eps.d/golfer.eps-8.pdf new file mode 100644 index 0000000..6ee9fec Binary files /dev/null and b/2023/infected/golfer.eps.d/golfer.eps-8.pdf differ diff --git a/2023/infected/golfer.eps.d/golfer.eps-9.pdf b/2023/infected/golfer.eps.d/golfer.eps-9.pdf new file mode 100644 index 0000000..d08ceb8 Binary files /dev/null and b/2023/infected/golfer.eps.d/golfer.eps-9.pdf differ diff --git a/2023/infected/snowflak.ps.d/snowflak.ps-1.pdf b/2023/infected/snowflak.ps.d/snowflak.ps-1.pdf new file mode 100644 index 0000000..168d4e5 Binary files /dev/null and b/2023/infected/snowflak.ps.d/snowflak.ps-1.pdf differ diff --git a/2023/infected/snowflak.ps.d/snowflak.ps-10.pdf b/2023/infected/snowflak.ps.d/snowflak.ps-10.pdf new file mode 100644 index 0000000..e5c15a6 Binary files /dev/null and b/2023/infected/snowflak.ps.d/snowflak.ps-10.pdf differ diff --git a/2023/infected/snowflak.ps.d/snowflak.ps-11.pdf b/2023/infected/snowflak.ps.d/snowflak.ps-11.pdf new file mode 100644 index 0000000..961db2d Binary files /dev/null and b/2023/infected/snowflak.ps.d/snowflak.ps-11.pdf differ diff --git a/2023/infected/snowflak.ps.d/snowflak.ps-12.pdf b/2023/infected/snowflak.ps.d/snowflak.ps-12.pdf new file mode 100644 index 0000000..51b94c1 Binary files /dev/null and b/2023/infected/snowflak.ps.d/snowflak.ps-12.pdf differ diff --git a/2023/infected/snowflak.ps.d/snowflak.ps-13.pdf b/2023/infected/snowflak.ps.d/snowflak.ps-13.pdf new file mode 100644 index 0000000..6865b39 Binary files /dev/null and b/2023/infected/snowflak.ps.d/snowflak.ps-13.pdf differ diff --git a/2023/infected/snowflak.ps.d/snowflak.ps-14.pdf b/2023/infected/snowflak.ps.d/snowflak.ps-14.pdf new file mode 100644 index 0000000..b87e65c Binary files /dev/null and b/2023/infected/snowflak.ps.d/snowflak.ps-14.pdf differ diff --git a/2023/infected/snowflak.ps.d/snowflak.ps-15.pdf b/2023/infected/snowflak.ps.d/snowflak.ps-15.pdf new file mode 100644 index 0000000..266036a Binary files /dev/null and b/2023/infected/snowflak.ps.d/snowflak.ps-15.pdf differ diff --git a/2023/infected/snowflak.ps.d/snowflak.ps-16.pdf b/2023/infected/snowflak.ps.d/snowflak.ps-16.pdf new file mode 100644 index 0000000..01c6fd7 Binary files /dev/null and b/2023/infected/snowflak.ps.d/snowflak.ps-16.pdf differ diff --git a/2023/infected/snowflak.ps.d/snowflak.ps-17.pdf b/2023/infected/snowflak.ps.d/snowflak.ps-17.pdf new file mode 100644 index 0000000..9a03604 Binary files /dev/null and b/2023/infected/snowflak.ps.d/snowflak.ps-17.pdf differ diff --git a/2023/infected/snowflak.ps.d/snowflak.ps-18.pdf b/2023/infected/snowflak.ps.d/snowflak.ps-18.pdf new file mode 100644 index 0000000..eb9711d Binary files /dev/null and b/2023/infected/snowflak.ps.d/snowflak.ps-18.pdf differ diff --git a/2023/infected/snowflak.ps.d/snowflak.ps-19.pdf b/2023/infected/snowflak.ps.d/snowflak.ps-19.pdf new file mode 100644 index 0000000..1cc0e27 Binary files /dev/null and b/2023/infected/snowflak.ps.d/snowflak.ps-19.pdf differ diff --git a/2023/infected/snowflak.ps.d/snowflak.ps-2.pdf b/2023/infected/snowflak.ps.d/snowflak.ps-2.pdf new file mode 100644 index 0000000..575bef0 Binary files /dev/null and b/2023/infected/snowflak.ps.d/snowflak.ps-2.pdf differ diff --git a/2023/infected/snowflak.ps.d/snowflak.ps-20.pdf b/2023/infected/snowflak.ps.d/snowflak.ps-20.pdf new file mode 100644 index 0000000..63ab0b7 Binary files /dev/null and b/2023/infected/snowflak.ps.d/snowflak.ps-20.pdf differ diff --git a/2023/infected/snowflak.ps.d/snowflak.ps-3.pdf b/2023/infected/snowflak.ps.d/snowflak.ps-3.pdf new file mode 100644 index 0000000..1b6483f Binary files /dev/null and b/2023/infected/snowflak.ps.d/snowflak.ps-3.pdf differ diff --git a/2023/infected/snowflak.ps.d/snowflak.ps-4.pdf b/2023/infected/snowflak.ps.d/snowflak.ps-4.pdf new file mode 100644 index 0000000..4d3f816 Binary files /dev/null and b/2023/infected/snowflak.ps.d/snowflak.ps-4.pdf differ diff --git a/2023/infected/snowflak.ps.d/snowflak.ps-5.pdf b/2023/infected/snowflak.ps.d/snowflak.ps-5.pdf new file mode 100644 index 0000000..13b257f Binary files /dev/null and b/2023/infected/snowflak.ps.d/snowflak.ps-5.pdf differ diff --git a/2023/infected/snowflak.ps.d/snowflak.ps-6.pdf b/2023/infected/snowflak.ps.d/snowflak.ps-6.pdf new file mode 100644 index 0000000..ca7eb62 Binary files /dev/null and b/2023/infected/snowflak.ps.d/snowflak.ps-6.pdf differ diff --git a/2023/infected/snowflak.ps.d/snowflak.ps-7.pdf b/2023/infected/snowflak.ps.d/snowflak.ps-7.pdf new file mode 100644 index 0000000..bd005bf Binary files /dev/null and b/2023/infected/snowflak.ps.d/snowflak.ps-7.pdf differ diff --git a/2023/infected/snowflak.ps.d/snowflak.ps-8.pdf b/2023/infected/snowflak.ps.d/snowflak.ps-8.pdf new file mode 100644 index 0000000..4c800d4 Binary files /dev/null and b/2023/infected/snowflak.ps.d/snowflak.ps-8.pdf differ diff --git a/2023/infected/snowflak.ps.d/snowflak.ps-9.pdf b/2023/infected/snowflak.ps.d/snowflak.ps-9.pdf new file mode 100644 index 0000000..3d216f4 Binary files /dev/null and b/2023/infected/snowflak.ps.d/snowflak.ps-9.pdf differ diff --git a/2023/infected/tiger.eps.d/tiger.eps-1.pdf b/2023/infected/tiger.eps.d/tiger.eps-1.pdf new file mode 100644 index 0000000..a3b7336 Binary files /dev/null and b/2023/infected/tiger.eps.d/tiger.eps-1.pdf differ diff --git a/2023/infected/tiger.eps.d/tiger.eps-10.pdf b/2023/infected/tiger.eps.d/tiger.eps-10.pdf new file mode 100644 index 0000000..7c49147 Binary files /dev/null and b/2023/infected/tiger.eps.d/tiger.eps-10.pdf differ diff --git a/2023/infected/tiger.eps.d/tiger.eps-11.pdf b/2023/infected/tiger.eps.d/tiger.eps-11.pdf new file mode 100644 index 0000000..69d4c3f Binary files /dev/null and b/2023/infected/tiger.eps.d/tiger.eps-11.pdf differ diff --git a/2023/infected/tiger.eps.d/tiger.eps-12.pdf b/2023/infected/tiger.eps.d/tiger.eps-12.pdf new file mode 100644 index 0000000..be6f430 Binary files /dev/null and b/2023/infected/tiger.eps.d/tiger.eps-12.pdf differ diff --git a/2023/infected/tiger.eps.d/tiger.eps-13.pdf b/2023/infected/tiger.eps.d/tiger.eps-13.pdf new file mode 100644 index 0000000..7b868cb Binary files /dev/null and b/2023/infected/tiger.eps.d/tiger.eps-13.pdf differ diff --git a/2023/infected/tiger.eps.d/tiger.eps-14.pdf b/2023/infected/tiger.eps.d/tiger.eps-14.pdf new file mode 100644 index 0000000..250bd77 Binary files /dev/null and b/2023/infected/tiger.eps.d/tiger.eps-14.pdf differ diff --git a/2023/infected/tiger.eps.d/tiger.eps-15.pdf b/2023/infected/tiger.eps.d/tiger.eps-15.pdf new file mode 100644 index 0000000..caaf825 Binary files /dev/null and b/2023/infected/tiger.eps.d/tiger.eps-15.pdf differ diff --git a/2023/infected/tiger.eps.d/tiger.eps-16.pdf b/2023/infected/tiger.eps.d/tiger.eps-16.pdf new file mode 100644 index 0000000..8cb7569 Binary files /dev/null and b/2023/infected/tiger.eps.d/tiger.eps-16.pdf differ diff --git a/2023/infected/tiger.eps.d/tiger.eps-17.pdf b/2023/infected/tiger.eps.d/tiger.eps-17.pdf new file mode 100644 index 0000000..565e8bf Binary files /dev/null and b/2023/infected/tiger.eps.d/tiger.eps-17.pdf differ diff --git a/2023/infected/tiger.eps.d/tiger.eps-18.pdf b/2023/infected/tiger.eps.d/tiger.eps-18.pdf new file mode 100644 index 0000000..d638bd8 Binary files /dev/null and b/2023/infected/tiger.eps.d/tiger.eps-18.pdf differ diff --git a/2023/infected/tiger.eps.d/tiger.eps-19.pdf b/2023/infected/tiger.eps.d/tiger.eps-19.pdf new file mode 100644 index 0000000..41fec10 Binary files /dev/null and b/2023/infected/tiger.eps.d/tiger.eps-19.pdf differ diff --git a/2023/infected/tiger.eps.d/tiger.eps-2.pdf b/2023/infected/tiger.eps.d/tiger.eps-2.pdf new file mode 100644 index 0000000..21b4651 Binary files /dev/null and b/2023/infected/tiger.eps.d/tiger.eps-2.pdf differ diff --git a/2023/infected/tiger.eps.d/tiger.eps-20.pdf b/2023/infected/tiger.eps.d/tiger.eps-20.pdf new file mode 100644 index 0000000..900daf8 Binary files /dev/null and b/2023/infected/tiger.eps.d/tiger.eps-20.pdf differ diff --git a/2023/infected/tiger.eps.d/tiger.eps-3.pdf b/2023/infected/tiger.eps.d/tiger.eps-3.pdf new file mode 100644 index 0000000..11eb60a Binary files /dev/null and b/2023/infected/tiger.eps.d/tiger.eps-3.pdf differ diff --git a/2023/infected/tiger.eps.d/tiger.eps-4.pdf b/2023/infected/tiger.eps.d/tiger.eps-4.pdf new file mode 100644 index 0000000..55348fc Binary files /dev/null and b/2023/infected/tiger.eps.d/tiger.eps-4.pdf differ diff --git a/2023/infected/tiger.eps.d/tiger.eps-5.pdf b/2023/infected/tiger.eps.d/tiger.eps-5.pdf new file mode 100644 index 0000000..92d8133 Binary files /dev/null and b/2023/infected/tiger.eps.d/tiger.eps-5.pdf differ diff --git a/2023/infected/tiger.eps.d/tiger.eps-6.pdf b/2023/infected/tiger.eps.d/tiger.eps-6.pdf new file mode 100644 index 0000000..7635ef4 Binary files /dev/null and b/2023/infected/tiger.eps.d/tiger.eps-6.pdf differ diff --git a/2023/infected/tiger.eps.d/tiger.eps-7.pdf b/2023/infected/tiger.eps.d/tiger.eps-7.pdf new file mode 100644 index 0000000..0ddf76e Binary files /dev/null and b/2023/infected/tiger.eps.d/tiger.eps-7.pdf differ diff --git a/2023/infected/tiger.eps.d/tiger.eps-8.pdf b/2023/infected/tiger.eps.d/tiger.eps-8.pdf new file mode 100644 index 0000000..9ab6f36 Binary files /dev/null and b/2023/infected/tiger.eps.d/tiger.eps-8.pdf differ diff --git a/2023/infected/tiger.eps.d/tiger.eps-9.pdf b/2023/infected/tiger.eps.d/tiger.eps-9.pdf new file mode 100644 index 0000000..9cbf225 Binary files /dev/null and b/2023/infected/tiger.eps.d/tiger.eps-9.pdf differ diff --git a/2023/infected/vasarely.ps.d/vasarely.ps-1.pdf b/2023/infected/vasarely.ps.d/vasarely.ps-1.pdf new file mode 100644 index 0000000..1244750 Binary files /dev/null and b/2023/infected/vasarely.ps.d/vasarely.ps-1.pdf differ diff --git a/2023/infected/vasarely.ps.d/vasarely.ps-10.pdf b/2023/infected/vasarely.ps.d/vasarely.ps-10.pdf new file mode 100644 index 0000000..a844597 Binary files /dev/null and b/2023/infected/vasarely.ps.d/vasarely.ps-10.pdf differ diff --git a/2023/infected/vasarely.ps.d/vasarely.ps-11.pdf b/2023/infected/vasarely.ps.d/vasarely.ps-11.pdf new file mode 100644 index 0000000..494e065 Binary files /dev/null and b/2023/infected/vasarely.ps.d/vasarely.ps-11.pdf differ diff --git a/2023/infected/vasarely.ps.d/vasarely.ps-12.pdf b/2023/infected/vasarely.ps.d/vasarely.ps-12.pdf new file mode 100644 index 0000000..ec57836 Binary files /dev/null and b/2023/infected/vasarely.ps.d/vasarely.ps-12.pdf differ diff --git a/2023/infected/vasarely.ps.d/vasarely.ps-13.pdf b/2023/infected/vasarely.ps.d/vasarely.ps-13.pdf new file mode 100644 index 0000000..f88d6cf Binary files /dev/null and b/2023/infected/vasarely.ps.d/vasarely.ps-13.pdf differ diff --git a/2023/infected/vasarely.ps.d/vasarely.ps-14.pdf b/2023/infected/vasarely.ps.d/vasarely.ps-14.pdf new file mode 100644 index 0000000..4348280 Binary files /dev/null and b/2023/infected/vasarely.ps.d/vasarely.ps-14.pdf differ diff --git a/2023/infected/vasarely.ps.d/vasarely.ps-15.pdf b/2023/infected/vasarely.ps.d/vasarely.ps-15.pdf new file mode 100644 index 0000000..6288fc0 Binary files /dev/null and b/2023/infected/vasarely.ps.d/vasarely.ps-15.pdf differ diff --git a/2023/infected/vasarely.ps.d/vasarely.ps-16.pdf b/2023/infected/vasarely.ps.d/vasarely.ps-16.pdf new file mode 100644 index 0000000..7c46c44 Binary files /dev/null and b/2023/infected/vasarely.ps.d/vasarely.ps-16.pdf differ diff --git a/2023/infected/vasarely.ps.d/vasarely.ps-17.pdf b/2023/infected/vasarely.ps.d/vasarely.ps-17.pdf new file mode 100644 index 0000000..f04633d Binary files /dev/null and b/2023/infected/vasarely.ps.d/vasarely.ps-17.pdf differ diff --git a/2023/infected/vasarely.ps.d/vasarely.ps-18.pdf b/2023/infected/vasarely.ps.d/vasarely.ps-18.pdf new file mode 100644 index 0000000..08e6669 Binary files /dev/null and b/2023/infected/vasarely.ps.d/vasarely.ps-18.pdf differ diff --git a/2023/infected/vasarely.ps.d/vasarely.ps-19.pdf b/2023/infected/vasarely.ps.d/vasarely.ps-19.pdf new file mode 100644 index 0000000..39d91b9 Binary files /dev/null and b/2023/infected/vasarely.ps.d/vasarely.ps-19.pdf differ diff --git a/2023/infected/vasarely.ps.d/vasarely.ps-2.pdf b/2023/infected/vasarely.ps.d/vasarely.ps-2.pdf new file mode 100644 index 0000000..299af41 Binary files /dev/null and b/2023/infected/vasarely.ps.d/vasarely.ps-2.pdf differ diff --git a/2023/infected/vasarely.ps.d/vasarely.ps-20.pdf b/2023/infected/vasarely.ps.d/vasarely.ps-20.pdf new file mode 100644 index 0000000..e4a08d8 Binary files /dev/null and b/2023/infected/vasarely.ps.d/vasarely.ps-20.pdf differ diff --git a/2023/infected/vasarely.ps.d/vasarely.ps-3.pdf b/2023/infected/vasarely.ps.d/vasarely.ps-3.pdf new file mode 100644 index 0000000..ab655ca Binary files /dev/null and b/2023/infected/vasarely.ps.d/vasarely.ps-3.pdf differ diff --git a/2023/infected/vasarely.ps.d/vasarely.ps-4.pdf b/2023/infected/vasarely.ps.d/vasarely.ps-4.pdf new file mode 100644 index 0000000..77f3a94 Binary files /dev/null and b/2023/infected/vasarely.ps.d/vasarely.ps-4.pdf differ diff --git a/2023/infected/vasarely.ps.d/vasarely.ps-5.pdf b/2023/infected/vasarely.ps.d/vasarely.ps-5.pdf new file mode 100644 index 0000000..707c310 Binary files /dev/null and b/2023/infected/vasarely.ps.d/vasarely.ps-5.pdf differ diff --git a/2023/infected/vasarely.ps.d/vasarely.ps-6.pdf b/2023/infected/vasarely.ps.d/vasarely.ps-6.pdf new file mode 100644 index 0000000..11e8146 Binary files /dev/null and b/2023/infected/vasarely.ps.d/vasarely.ps-6.pdf differ diff --git a/2023/infected/vasarely.ps.d/vasarely.ps-7.pdf b/2023/infected/vasarely.ps.d/vasarely.ps-7.pdf new file mode 100644 index 0000000..a4e92c3 Binary files /dev/null and b/2023/infected/vasarely.ps.d/vasarely.ps-7.pdf differ diff --git a/2023/infected/vasarely.ps.d/vasarely.ps-8.pdf b/2023/infected/vasarely.ps.d/vasarely.ps-8.pdf new file mode 100644 index 0000000..c7d13e6 Binary files /dev/null and b/2023/infected/vasarely.ps.d/vasarely.ps-8.pdf differ diff --git a/2023/infected/vasarely.ps.d/vasarely.ps-9.pdf b/2023/infected/vasarely.ps.d/vasarely.ps-9.pdf new file mode 100644 index 0000000..58d80d2 Binary files /dev/null and b/2023/infected/vasarely.ps.d/vasarely.ps-9.pdf differ diff --git a/2023/infected/waterfal.ps.d/waterfal.ps-1.pdf b/2023/infected/waterfal.ps.d/waterfal.ps-1.pdf new file mode 100644 index 0000000..c23e9a1 Binary files /dev/null and b/2023/infected/waterfal.ps.d/waterfal.ps-1.pdf differ diff --git a/2023/infected/waterfal.ps.d/waterfal.ps-10.pdf b/2023/infected/waterfal.ps.d/waterfal.ps-10.pdf new file mode 100644 index 0000000..4ab0a8e Binary files /dev/null and b/2023/infected/waterfal.ps.d/waterfal.ps-10.pdf differ diff --git a/2023/infected/waterfal.ps.d/waterfal.ps-11.pdf b/2023/infected/waterfal.ps.d/waterfal.ps-11.pdf new file mode 100644 index 0000000..44935a3 Binary files /dev/null and b/2023/infected/waterfal.ps.d/waterfal.ps-11.pdf differ diff --git a/2023/infected/waterfal.ps.d/waterfal.ps-12.pdf b/2023/infected/waterfal.ps.d/waterfal.ps-12.pdf new file mode 100644 index 0000000..cce6e9d Binary files /dev/null and b/2023/infected/waterfal.ps.d/waterfal.ps-12.pdf differ diff --git a/2023/infected/waterfal.ps.d/waterfal.ps-13.pdf b/2023/infected/waterfal.ps.d/waterfal.ps-13.pdf new file mode 100644 index 0000000..5a575c0 Binary files /dev/null and b/2023/infected/waterfal.ps.d/waterfal.ps-13.pdf differ diff --git a/2023/infected/waterfal.ps.d/waterfal.ps-14.pdf b/2023/infected/waterfal.ps.d/waterfal.ps-14.pdf new file mode 100644 index 0000000..a7b6bcc Binary files /dev/null and b/2023/infected/waterfal.ps.d/waterfal.ps-14.pdf differ diff --git a/2023/infected/waterfal.ps.d/waterfal.ps-15.pdf b/2023/infected/waterfal.ps.d/waterfal.ps-15.pdf new file mode 100644 index 0000000..c59cbbe Binary files /dev/null and b/2023/infected/waterfal.ps.d/waterfal.ps-15.pdf differ diff --git a/2023/infected/waterfal.ps.d/waterfal.ps-16.pdf b/2023/infected/waterfal.ps.d/waterfal.ps-16.pdf new file mode 100644 index 0000000..b3a75b4 Binary files /dev/null and b/2023/infected/waterfal.ps.d/waterfal.ps-16.pdf differ diff --git a/2023/infected/waterfal.ps.d/waterfal.ps-17.pdf b/2023/infected/waterfal.ps.d/waterfal.ps-17.pdf new file mode 100644 index 0000000..3f4ba6a Binary files /dev/null and b/2023/infected/waterfal.ps.d/waterfal.ps-17.pdf differ diff --git a/2023/infected/waterfal.ps.d/waterfal.ps-18.pdf b/2023/infected/waterfal.ps.d/waterfal.ps-18.pdf new file mode 100644 index 0000000..925b186 Binary files /dev/null and b/2023/infected/waterfal.ps.d/waterfal.ps-18.pdf differ diff --git a/2023/infected/waterfal.ps.d/waterfal.ps-19.pdf b/2023/infected/waterfal.ps.d/waterfal.ps-19.pdf new file mode 100644 index 0000000..c1ae6c8 Binary files /dev/null and b/2023/infected/waterfal.ps.d/waterfal.ps-19.pdf differ diff --git a/2023/infected/waterfal.ps.d/waterfal.ps-2.pdf b/2023/infected/waterfal.ps.d/waterfal.ps-2.pdf new file mode 100644 index 0000000..eca9dc2 Binary files /dev/null and b/2023/infected/waterfal.ps.d/waterfal.ps-2.pdf differ diff --git a/2023/infected/waterfal.ps.d/waterfal.ps-20.pdf b/2023/infected/waterfal.ps.d/waterfal.ps-20.pdf new file mode 100644 index 0000000..6fdc0eb Binary files /dev/null and b/2023/infected/waterfal.ps.d/waterfal.ps-20.pdf differ diff --git a/2023/infected/waterfal.ps.d/waterfal.ps-3.pdf b/2023/infected/waterfal.ps.d/waterfal.ps-3.pdf new file mode 100644 index 0000000..4a35745 Binary files /dev/null and b/2023/infected/waterfal.ps.d/waterfal.ps-3.pdf differ diff --git a/2023/infected/waterfal.ps.d/waterfal.ps-4.pdf b/2023/infected/waterfal.ps.d/waterfal.ps-4.pdf new file mode 100644 index 0000000..d696bd8 Binary files /dev/null and b/2023/infected/waterfal.ps.d/waterfal.ps-4.pdf differ diff --git a/2023/infected/waterfal.ps.d/waterfal.ps-5.pdf b/2023/infected/waterfal.ps.d/waterfal.ps-5.pdf new file mode 100644 index 0000000..c15878e Binary files /dev/null and b/2023/infected/waterfal.ps.d/waterfal.ps-5.pdf differ diff --git a/2023/infected/waterfal.ps.d/waterfal.ps-6.pdf b/2023/infected/waterfal.ps.d/waterfal.ps-6.pdf new file mode 100644 index 0000000..2d99f1d Binary files /dev/null and b/2023/infected/waterfal.ps.d/waterfal.ps-6.pdf differ diff --git a/2023/infected/waterfal.ps.d/waterfal.ps-7.pdf b/2023/infected/waterfal.ps.d/waterfal.ps-7.pdf new file mode 100644 index 0000000..da10c0f Binary files /dev/null and b/2023/infected/waterfal.ps.d/waterfal.ps-7.pdf differ diff --git a/2023/infected/waterfal.ps.d/waterfal.ps-8.pdf b/2023/infected/waterfal.ps.d/waterfal.ps-8.pdf new file mode 100644 index 0000000..39f1842 Binary files /dev/null and b/2023/infected/waterfal.ps.d/waterfal.ps-8.pdf differ diff --git a/2023/infected/waterfal.ps.d/waterfal.ps-9.pdf b/2023/infected/waterfal.ps.d/waterfal.ps-9.pdf new file mode 100644 index 0000000..d6f404e Binary files /dev/null and b/2023/infected/waterfal.ps.d/waterfal.ps-9.pdf differ diff --git a/2023/multiples.sh b/2023/multiples.sh new file mode 100755 index 0000000..65c3454 --- /dev/null +++ b/2023/multiples.sh @@ -0,0 +1,15 @@ +mkdir -p ./uninfected +mkdir -p ./infected + +# *ps for .ps and .eps +for example in ./ghostscript-examples/**ps; do + echo "-----> ${example}" + outdir="./infected/$(basename ${example}).d" + mkdir -p "${outdir}" + for i in {1..20} + do + gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER \ + -sOutputFile="./${outdir}/${example##*/}-${i}.pdf" \ + ./payload.ps "${example}" + done +done
filodej/rpcpp
d5a106824985c11747cc90846ba74bfa6b0466d9
implemeted async call buffering added benchmark results
diff --git a/bin/test.py b/bin/test.py index 2dacac5..ea58366 100644 --- a/bin/test.py +++ b/bin/test.py @@ -1,186 +1,219 @@ import sys import os.path sys.path.append( os.path.abspath( './release') ) import getopt import time import rpcppy import rpyc import rpyc.utils.server -def py_synch_benchmark( echo, val, count ): - """Python implemented benchmark for synchronous calls""" +def py_synch_indirect_benchmark( echo, val, count ): + """Python implemented unbuffered benchmark for synchronous indirect calls""" start = time.clock() for i in xrange( count ): assert echo.call( val ) == val return time.clock() - start + +def py_synch_direct_benchmark( echo, val, count ): + """Python implemented unbuffered benchmark for synchronous direct calls""" + call = echo.call + start = time.clock() + for i in xrange( count ): + assert call( val ) == val + return time.clock() - start + +def _py_buffered_benchmark( call, val, check_val, count, buffer_size = 512 ): + """Python implemented benchmark with result buffering""" + start = time.clock() + proxies = [] + while count or proxies: + num_inserted = min( buffer_size - len( proxies ), count ) + proxies.extend( call( val ) for i in xrange( num_inserted ) ) +# print len( proxies ), + proxies = filter( check_val, proxies ) + count -= num_inserted +# print len( proxies ), count + return time.clock() - start + +def py_synch_buffered_benchmark( echo, val, count ): + """Python implemented benchmark with result buffering""" + def check_val( result ): + assert result == val + return False + return _py_buffered_benchmark( echo.call, val, check_val, count ) -def py_asynch_benchmark( echo, val, count ): - """Python implemented benchmark for asynchronous RPyC calls""" - def check_val( proxy ): - if proxy.ready: - assert proxy.value == val - return False - else: - return True - start = time.clock() - proxies = [ rpyc.async( echo.call )( val ) for i in xrange( count ) ] - while proxies: - proxies = filter( check_val, proxies ) - if proxies: - print len(proxies) - return time.clock() - start - +def py_asynch_buffered_benchmark( echo, val, count ): + """Python implemented benchmark with asynch proxy buffering""" + def check_val( proxy ): + if proxy.ready: + assert proxy.value == val + return False + else: + return True + return _py_buffered_benchmark( rpyc.async( echo.call ), val, check_val, count ) + class adapter_factory( object ): """Factory adapter (swig delegate cannot be directly marshalled by RPyC) it is necessary to create an adapter - python wrapper - delegating the calls""" def __init__( self, factory ): self.factory = factory def create_echo_int( self ): return adapter_factory._wrap( rpcppy.echo_int )( self.factory.create_echo_int() ) def create_echo_str( self ): return adapter_factory._wrap( rpcppy.echo_str )( self.factory.create_echo_str() ) @staticmethod def _wrap( base ): class _adapter( base ): def __init__( self, next ): base.__init__( self ) self._next = next def call( self, val ): return self._next.call( val ) return _adapter class remote_factory( object ): """Factory for remote (RPyC calls)""" def __init__( self, host, port ): self.conn = rpyc.classic.connect( host, port ) mod = self.conn.modules["rpcppy"] self.create_echo_int = mod.create_echo_int self.create_echo_str = mod.create_echo_str def advanced_test( factory, fn_bench_int, fn_bench_str, treshold, verbose ): """Each test consists of following tests: - integer sub-test - string sub-test for several string lengths (8, 16, ... 128) """ def deref( ptr ): try: return ptr.__deref__() except: return ptr def do_benchmark( echo, fnbench, val ): i = 10 while 2**(i+1) <= sys.maxint: i += 1 t = fnbench( deref(echo), val, 2**i ) if t > treshold: break print '%f calls/sec.' % ( float(2**i)/t ) if verbose: print '\t\t(%d calls in %f seconds)' % ( 2**i, t ) print '\tcall(int)\t\t', do_benchmark( factory.create_echo_int(), fn_bench_int, 42 ) for i in range( 3, 8 ): print '\tcall(str[len=%d])\t' % ( 2**i ), do_benchmark( factory.create_echo_str(), fn_bench_str, 2**i * 'X' ) def parse_options(): """\ Usage: python test.py <options> Options: -h, --help ... prints this message -m, --mode ... mode (one of 'local', 'client', server) -H, --hostnames... comma separated list of servers' hostnames (default 'localhost') -p, --port ... rpyc port (default 18861) -t, --treshold ... benchmark treshold (default 5.0 sec.) -v, --verbose ... detailed test results printed (disabled by default) """ try: opts, args = getopt.getopt(sys.argv[1:], "hH:m:p:t:v", ["help", "hostnames=", "mode=", "port=", "treshold=", "verbose"]) except getopt.GetoptError, err: print str(err) # will print something like "option -a not recognized" print parse_options.__doc__ sys.exit(2) hostnames = '' port = 18861 mode = 'local' treshold = 5.0 verbose = False for o, a in opts: if o in ("-h", "--help"): print parse_options.__doc__ sys.exit() elif o in ("-p", "--port"): port = a elif o in ("-t", "--treshold"): treshold = float(a) elif o in ("-v", "--verbose"): verbose = True elif o in ("-H", "--hostnames"): hostnames = a elif o in ("-m", "--mode"): if a not in ('local', 'client', 'server'): print 'unknown mode:', a print parse_options.__doc__ sys.exit(2) mode = a else: assert False, "unhandled option" if mode == 'client' and not hostnames: hostnames = 'localhost' elif mode == 'server' and hostnames: print 'cannot specify hostnames in server mode' sys.exit(2) return mode, hostnames, port, treshold, verbose def build_test_suite( hostnames, port ): """Builds whole test suite (a set of individual tests)""" # in-process tests suite = [ ( 'in-process calls [c++ -> c++]:', rpcppy, rpcppy.benchmark_int, rpcppy.benchmark_str ), - ( 'in-process calls [python -> c++]:', rpcppy, py_synch_benchmark, py_synch_benchmark ), - ( 'in-process calls [c++ -> python -> c++]:', adapter_factory( rpcppy ), rpcppy.benchmark_int, rpcppy.benchmark_str ) ] + ( 'in-process direct calls [python -> c++]:', rpcppy, py_synch_direct_benchmark, py_synch_direct_benchmark ), + ( 'in-process indirect calls [python -> c++]:', rpcppy, py_synch_indirect_benchmark, py_synch_indirect_benchmark ), + ( 'in-process calls [c++ -> python -> c++]:', adapter_factory( rpcppy ), rpcppy.benchmark_int, rpcppy.benchmark_str ) ] if hostnames: # out-of-process tests for each specified server for hostname in hostnames.split(','): - suite.append( ( - 'out-of-process "%s" synch calls [c++ -> python -> RPC -> python -> c++]:' % hostname, - adapter_factory( remote_factory( hostname, port ) ), - rpcppy.benchmark_int, - rpcppy.benchmark_str ) ) - suite.append( ( - 'out-of-process "%s" synch calls [python -> RPC -> python -> c++]:' % hostname, - remote_factory( hostname, port ), - py_synch_benchmark, - py_synch_benchmark ) ) - suite.append( ( - 'out-of-process "%s" asynch calls [python -> RPC -> python -> c++]:' % hostname, - remote_factory( hostname, port ), - py_asynch_benchmark, - py_asynch_benchmark ) ) + suite.append( ( + 'out-of-process "%s" synch calls [c++ -> python -> RPC -> python -> c++]:' % hostname, + adapter_factory( remote_factory( hostname, port ) ), + rpcppy.benchmark_int, + rpcppy.benchmark_str ) ) + suite.append( ( + 'out-of-process "%s" synch indirect calls [python -> RPC -> python -> c++]:' % hostname, + remote_factory( hostname, port ), + py_synch_indirect_benchmark, + py_synch_indirect_benchmark ) ) + suite.append( ( + 'out-of-process "%s" synch direct calls [python -> RPC -> python -> c++]:' % hostname, + remote_factory( hostname, port ), + py_synch_direct_benchmark, + py_synch_direct_benchmark ) ) + suite.append( ( + 'out-of-process "%s" buffered synch calls [python -> RPC -> python -> c++]:' % hostname, + remote_factory( hostname, port ), + py_synch_buffered_benchmark, + py_synch_buffered_benchmark ) ) + suite.append( ( + 'out-of-process "%s" buffered asynch calls [python -> RPC -> python -> c++]:' % hostname, + remote_factory( hostname, port ), + py_asynch_buffered_benchmark, + py_asynch_buffered_benchmark ) ) return suite def run_test_suite( suite, treshold = 5.0, verbose = False ): """Runs all given tests""" for desc, f, fn_bench_int, fn_bench_str in suite: print desc advanced_test( f, fn_bench_int, fn_bench_str, treshold, verbose ) def test_server( port ): """Launches test server""" ts = rpyc.utils.server.ThreadedServer( rpyc.SlaveService, port = port ) ts.start() if __name__ == '__main__': mode, hostnames, port, treshold, verbose = parse_options() if mode == 'server': assert not hostnames test_server( port ) else: assert mode != 'client' or hostnames run_test_suite( build_test_suite( hostnames, port ), treshold, verbose ) diff --git a/results.txt b/results.txt new file mode 100644 index 0000000..e94fe3b --- /dev/null +++ b/results.txt @@ -0,0 +1,144 @@ + +D:\starteam\docplatform\rpcpp\bin>test.py -H localhost,10.0.2.2,prg3k04 +in-process calls [c++ -> c++]: + call(int) 416340373.788290 calls/sec. + call(str[len=8]) 14364054.794521 calls/sec. + call(str[len=16]) 4277719.530852 calls/sec. + call(str[len=32]) 3969059.853324 calls/sec. + call(str[len=64]) 3925872.469872 calls/sec. + call(str[len=128]) 3621242.391539 calls/sec. +in-process direct calls [python -> c++]: + call(int) 1458452.418937 calls/sec. + call(str[len=8]) 800563.529584 calls/sec. + call(str[len=16]) 468172.710771 calls/sec. + call(str[len=32]) 471741.048997 calls/sec. + call(str[len=64]) 455922.906647 calls/sec. + call(str[len=128]) 434606.085993 calls/sec. +in-process indirect calls [python -> c++]: + call(int) 1077910.527897 calls/sec. + call(str[len=8]) 665014.285316 calls/sec. + call(str[len=16]) 424980.272230 calls/sec. + call(str[len=32]) 426478.169133 calls/sec. + call(str[len=64]) 412849.407006 calls/sec. + call(str[len=128]) 394166.728099 calls/sec. +in-process calls [c++ -> python -> c++]: + call(int) 496132.481665 calls/sec. + call(str[len=8]) 335544.320000 calls/sec. + call(str[len=16]) 223696.213333 calls/sec. + call(str[len=32]) 224438.356164 calls/sec. + call(str[len=64]) 221101.950448 calls/sec. + call(str[len=128]) 217524.323203 calls/sec. +out-of-process "localhost" synch calls [c++ -> python -> RPC -> python -> c++]: + call(int) 1801.627447 calls/sec. + call(str[len=8]) 1783.195472 calls/sec. + call(str[len=16]) 1777.199262 calls/sec. + call(str[len=32]) 1771.243243 calls/sec. + call(str[len=64]) 1774.312324 calls/sec. + call(str[len=128]) 1771.051778 calls/sec. +out-of-process "localhost" synch indirect calls [python -> RPC -> python -> c++] +: + call(int) 1827.128589 calls/sec. + call(str[len=8]) 1812.710256 calls/sec. + call(str[len=16]) 1801.582771 calls/sec. + call(str[len=32]) 1793.988124 calls/sec. + call(str[len=64]) 1802.146802 calls/sec. + call(str[len=128]) 1796.239431 calls/sec. +out-of-process "localhost" synch direct calls [python -> RPC -> python -> c++]: + call(int) 4855.299259 calls/sec. + call(str[len=8]) 4757.274356 calls/sec. + call(str[len=16]) 4703.827548 calls/sec. + call(str[len=32]) 4632.139542 calls/sec. + call(str[len=64]) 4680.109954 calls/sec. + call(str[len=128]) 4619.936432 calls/sec. +out-of-process "localhost" buffered synch calls [python -> RPC -> python -> c++] +: + call(int) 4856.348471 calls/sec. + call(str[len=8]) 4650.203720 calls/sec. + call(str[len=16]) 4612.721776 calls/sec. + call(str[len=32]) 4633.573750 calls/sec. + call(str[len=64]) 4632.037284 calls/sec. + call(str[len=128]) 4657.999418 calls/sec. +out-of-process "localhost" buffered asynch calls [python -> RPC -> python -> c++ +]: + call(int) 8885.482097 calls/sec. + call(str[len=8]) 8782.766706 calls/sec. + call(str[len=16]) 8786.995314 calls/sec. + call(str[len=32]) 8804.157808 calls/sec. + call(str[len=64]) 8758.325900 calls/sec. + call(str[len=128]) 8667.702515 calls/sec. +out-of-process "10.0.2.2" synch calls [c++ -> python -> RPC -> python -> c++]: + call(int) 1263.222822 calls/sec. + call(str[len=8]) 1245.363332 calls/sec. + call(str[len=16]) 1257.213014 calls/sec. + call(str[len=32]) 1257.213014 calls/sec. + call(str[len=64]) 1254.325524 calls/sec. + call(str[len=128]) 1248.209660 calls/sec. +out-of-process "10.0.2.2" synch indirect calls [python -> RPC -> python -> c++]: + + call(int) 1257.788742 calls/sec. + call(str[len=8]) 1252.081516 calls/sec. + call(str[len=16]) 1250.575315 calls/sec. + call(str[len=32]) 1248.927878 calls/sec. + call(str[len=64]) 1248.477518 calls/sec. + call(str[len=128]) 1246.097418 calls/sec. +out-of-process "10.0.2.2" synch direct calls [python -> RPC -> python -> c++]: + call(int) 3736.244089 calls/sec. + call(str[len=8]) 3624.202574 calls/sec. + call(str[len=16]) 3627.128843 calls/sec. + call(str[len=32]) 3618.339909 calls/sec. + call(str[len=64]) 3609.958291 calls/sec. + call(str[len=128]) 3593.370577 calls/sec. +out-of-process "10.0.2.2" buffered synch calls [python -> RPC -> python -> c++]: + + call(int) 3715.204646 calls/sec. + call(str[len=8]) 3619.164876 calls/sec. + call(str[len=16]) 3613.779635 calls/sec. + call(str[len=32]) 3604.378022 calls/sec. + call(str[len=64]) 3601.356466 calls/sec. + call(str[len=128]) 3594.650916 calls/sec. +out-of-process "10.0.2.2" buffered asynch calls [python -> RPC -> python -> c++] +: + call(int) 9165.990399 calls/sec. + call(str[len=8]) 9046.258125 calls/sec. + call(str[len=16]) 9049.851642 calls/sec. + call(str[len=32]) 9047.724533 calls/sec. + call(str[len=64]) 8927.305098 calls/sec. + call(str[len=128]) 8249.053609 calls/sec. +out-of-process "prg3k04" synch calls [c++ -> python -> RPC -> python -> c++]: + call(int) 506.053867 calls/sec. + call(str[len=8]) 487.270997 calls/sec. + call(str[len=16]) 488.142057 calls/sec. + call(str[len=32]) 495.523833 calls/sec. + call(str[len=64]) 493.672412 calls/sec. + call(str[len=128]) 485.423086 calls/sec. +out-of-process "prg3k04" synch indirect calls [python -> RPC -> python -> c++]: + call(int) 500.636917 calls/sec. + call(str[len=8]) 510.168776 calls/sec. + call(str[len=16]) 498.240439 calls/sec. + call(str[len=32]) 486.192609 calls/sec. + call(str[len=64]) 509.393537 calls/sec. + call(str[len=128]) 495.204130 calls/sec. +out-of-process "prg3k04" synch direct calls [python -> RPC -> python -> c++]: + call(int) 1477.648605 calls/sec. + call(str[len=8]) 1395.251399 calls/sec. + call(str[len=16]) 1424.747611 calls/sec. + call(str[len=32]) 1452.396085 calls/sec. + call(str[len=64]) 1379.601242 calls/sec. + call(str[len=128]) 1375.746616 calls/sec. +out-of-process "prg3k04" buffered synch calls [python -> RPC -> python -> c++]: + call(int) 1496.729184 calls/sec. + call(str[len=8]) 1498.203518 calls/sec. + call(str[len=16]) 1460.120720 calls/sec. + call(str[len=32]) 1403.391747 calls/sec. + call(str[len=64]) 1442.221234 calls/sec. + call(str[len=128]) 1462.295190 calls/sec. +out-of-process "prg3k04" buffered asynch calls [python -> RPC -> python -> c++]: + + call(int) 6514.813030 calls/sec. + call(str[len=8]) 6264.466887 calls/sec. + call(str[len=16]) 6266.069012 calls/sec. + call(str[len=32]) 6267.281860 calls/sec. + call(str[len=64]) 6425.197500 calls/sec. + call(str[len=128]) 5953.323319 calls/sec. + +D:\starteam\docplatform\rpcpp\bin> \ No newline at end of file
filodej/rpcpp
9acf9066aeadf4a9cae0597d0750afc998462b1d
fix in teh test descriptions
diff --git a/bin/test.py b/bin/test.py index ea49c98..2dacac5 100644 --- a/bin/test.py +++ b/bin/test.py @@ -1,183 +1,186 @@ import sys import os.path sys.path.append( os.path.abspath( './release') ) import getopt import time import rpcppy import rpyc import rpyc.utils.server def py_synch_benchmark( echo, val, count ): """Python implemented benchmark for synchronous calls""" start = time.clock() for i in xrange( count ): assert echo.call( val ) == val return time.clock() - start def py_asynch_benchmark( echo, val, count ): """Python implemented benchmark for asynchronous RPyC calls""" def check_val( proxy ): if proxy.ready: assert proxy.value == val return False else: return True start = time.clock() proxies = [ rpyc.async( echo.call )( val ) for i in xrange( count ) ] while proxies: proxies = filter( check_val, proxies ) + if proxies: + print len(proxies) return time.clock() - start class adapter_factory( object ): """Factory adapter (swig delegate cannot be directly marshalled by RPyC) it is necessary to create an adapter - python wrapper - delegating the calls""" def __init__( self, factory ): self.factory = factory def create_echo_int( self ): return adapter_factory._wrap( rpcppy.echo_int )( self.factory.create_echo_int() ) def create_echo_str( self ): return adapter_factory._wrap( rpcppy.echo_str )( self.factory.create_echo_str() ) @staticmethod def _wrap( base ): class _adapter( base ): def __init__( self, next ): base.__init__( self ) self._next = next def call( self, val ): return self._next.call( val ) return _adapter class remote_factory( object ): """Factory for remote (RPyC calls)""" def __init__( self, host, port ): self.conn = rpyc.classic.connect( host, port ) mod = self.conn.modules["rpcppy"] self.create_echo_int = mod.create_echo_int self.create_echo_str = mod.create_echo_str def advanced_test( factory, fn_bench_int, fn_bench_str, treshold, verbose ): """Each test consists of following tests: - integer sub-test - string sub-test for several string lengths (8, 16, ... 128) """ def deref( ptr ): try: return ptr.__deref__() except: return ptr def do_benchmark( echo, fnbench, val ): i = 10 while 2**(i+1) <= sys.maxint: i += 1 t = fnbench( deref(echo), val, 2**i ) if t > treshold: break print '%f calls/sec.' % ( float(2**i)/t ) if verbose: print '\t\t(%d calls in %f seconds)' % ( 2**i, t ) print '\tcall(int)\t\t', do_benchmark( factory.create_echo_int(), fn_bench_int, 42 ) for i in range( 3, 8 ): print '\tcall(str[len=%d])\t' % ( 2**i ), do_benchmark( factory.create_echo_str(), fn_bench_str, 2**i * 'X' ) def parse_options(): """\ Usage: python test.py <options> Options: -h, --help ... prints this message -m, --mode ... mode (one of 'local', 'client', server) -H, --hostnames... comma separated list of servers' hostnames (default 'localhost') -p, --port ... rpyc port (default 18861) -t, --treshold ... benchmark treshold (default 5.0 sec.) -v, --verbose ... detailed test results printed (disabled by default) """ try: opts, args = getopt.getopt(sys.argv[1:], "hH:m:p:t:v", ["help", "hostnames=", "mode=", "port=", "treshold=", "verbose"]) except getopt.GetoptError, err: print str(err) # will print something like "option -a not recognized" print parse_options.__doc__ sys.exit(2) hostnames = '' port = 18861 mode = 'local' treshold = 5.0 verbose = False for o, a in opts: if o in ("-h", "--help"): print parse_options.__doc__ sys.exit() elif o in ("-p", "--port"): port = a elif o in ("-t", "--treshold"): treshold = float(a) elif o in ("-v", "--verbose"): verbose = True elif o in ("-H", "--hostnames"): hostnames = a elif o in ("-m", "--mode"): if a not in ('local', 'client', 'server'): print 'unknown mode:', a print parse_options.__doc__ sys.exit(2) mode = a else: assert False, "unhandled option" if mode == 'client' and not hostnames: hostnames = 'localhost' elif mode == 'server' and hostnames: print 'cannot specify hostnames in server mode' sys.exit(2) return mode, hostnames, port, treshold, verbose def build_test_suite( hostnames, port ): """Builds whole test suite (a set of individual tests)""" # in-process tests suite = [ ( 'in-process calls [c++ -> c++]:', rpcppy, rpcppy.benchmark_int, rpcppy.benchmark_str ), ( 'in-process calls [python -> c++]:', rpcppy, py_synch_benchmark, py_synch_benchmark ), ( 'in-process calls [c++ -> python -> c++]:', adapter_factory( rpcppy ), rpcppy.benchmark_int, rpcppy.benchmark_str ) ] - # out-of-process tests for each specified server - for hostname in hostnames.split(','): - suite.append( ( - 'out-of-process localhost synch calls [c++ -> python -> RPC -> python -> c++]:', - adapter_factory( remote_factory( hostname, port ) ), - rpcppy.benchmark_int, - rpcppy.benchmark_str ) ) - suite.append( ( - 'out-of-process localhost synch calls [python -> RPC -> python -> c++]:', - remote_factory( hostname, port ), - py_synch_benchmark, - py_synch_benchmark ) ) - suite.append( ( - 'out-of-process localhost asynch calls [python -> RPC -> python -> c++]:', - remote_factory( hostname, port ), - py_asynch_benchmark, - py_asynch_benchmark ) ) + if hostnames: + # out-of-process tests for each specified server + for hostname in hostnames.split(','): + suite.append( ( + 'out-of-process "%s" synch calls [c++ -> python -> RPC -> python -> c++]:' % hostname, + adapter_factory( remote_factory( hostname, port ) ), + rpcppy.benchmark_int, + rpcppy.benchmark_str ) ) + suite.append( ( + 'out-of-process "%s" synch calls [python -> RPC -> python -> c++]:' % hostname, + remote_factory( hostname, port ), + py_synch_benchmark, + py_synch_benchmark ) ) + suite.append( ( + 'out-of-process "%s" asynch calls [python -> RPC -> python -> c++]:' % hostname, + remote_factory( hostname, port ), + py_asynch_benchmark, + py_asynch_benchmark ) ) return suite def run_test_suite( suite, treshold = 5.0, verbose = False ): """Runs all given tests""" for desc, f, fn_bench_int, fn_bench_str in suite: print desc advanced_test( f, fn_bench_int, fn_bench_str, treshold, verbose ) def test_server( port ): """Launches test server""" ts = rpyc.utils.server.ThreadedServer( rpyc.SlaveService, port = port ) ts.start() if __name__ == '__main__': mode, hostnames, port, treshold, verbose = parse_options() if mode == 'server': assert not hostnames test_server( port ) else: assert mode != 'client' or hostnames run_test_suite( build_test_suite( hostnames, port ), treshold, verbose )
filodej/rpcpp
bca852ab37adcda36b14fc2b97636d7a21bf1e49
Added documentation to the python test. Added asynchronous tests.
diff --git a/bin/test.py b/bin/test.py index 087a749..ea49c98 100644 --- a/bin/test.py +++ b/bin/test.py @@ -1,132 +1,183 @@ import sys -import os.path -sys.path.append( os.path.abspath( './relwithdebinfo') ) +import os.path +sys.path.append( os.path.abspath( './release') ) import getopt -import new +import time import rpcppy import rpyc import rpyc.utils.server -def deref( ptr ): - try: - return ptr.__deref__() - except: - return ptr +def py_synch_benchmark( echo, val, count ): + """Python implemented benchmark for synchronous calls""" + start = time.clock() + for i in xrange( count ): + assert echo.call( val ) == val + return time.clock() - start -def _make_echo_adapter( base ): - class _adapter( base ): - def __init__( self, next ): - base.__init__( self ) - self._next = next - def call( self, val ): - return self._next.call( val ) - return _adapter +def py_asynch_benchmark( echo, val, count ): + """Python implemented benchmark for asynchronous RPyC calls""" + def check_val( proxy ): + if proxy.ready: + assert proxy.value == val + return False + else: + return True + start = time.clock() + proxies = [ rpyc.async( echo.call )( val ) for i in xrange( count ) ] + while proxies: + proxies = filter( check_val, proxies ) + return time.clock() - start class adapter_factory( object ): - echo_int = _make_echo_adapter( rpcppy.echo_int ) - echo_str = _make_echo_adapter( rpcppy.echo_str ) - - def __init__( self, factory = rpcppy ): - self.factory = factory - + """Factory adapter (swig delegate cannot be directly marshalled by RPyC) + it is necessary to create an adapter - python wrapper - delegating the calls""" + def __init__( self, factory ): + self.factory = factory + def create_echo_int( self ): - return adapter_factory.echo_int( self.factory.create_echo_int() ) - + return adapter_factory._wrap( rpcppy.echo_int )( self.factory.create_echo_int() ) + def create_echo_str( self ): - return adapter_factory.echo_str( self.factory.create_echo_str() ) + return adapter_factory._wrap( rpcppy.echo_str )( self.factory.create_echo_str() ) + + @staticmethod + def _wrap( base ): + class _adapter( base ): + def __init__( self, next ): + base.__init__( self ) + self._next = next + def call( self, val ): + return self._next.call( val ) + return _adapter class remote_factory( object ): + """Factory for remote (RPyC calls)""" def __init__( self, host, port ): - self.conn = rpyc.classic.connect( host, port ) - mod = self.conn.modules["rpcppy"] - self.create_echo_int = mod.create_echo_int - self.create_echo_str = mod.create_echo_str - -def simple_test( factory = rpcppy ): - ei = factory.create_echo_int() - assert 42 == ei.call( 42 ) - - es = factory.create_echo_str() - assert '42' == es.call( '42' ) + self.conn = rpyc.classic.connect( host, port ) + mod = self.conn.modules["rpcppy"] + self.create_echo_int = mod.create_echo_int + self.create_echo_str = mod.create_echo_str -def advanced_test( factory = rpcppy, treshold = 5.0, verbose = False ): - def benchmark( echo, fn, val ): - i = 10 - while 2**(i+1) <= sys.maxint: - i += 1 - t = fn( deref(echo), val, 2**i ) - if t > treshold: - break - print '%f calls/sec.' % ( float(2**i)/t ) - if verbose: - print '\t\t(%d calls in %f seconds)' % ( 2**i, t ) +def advanced_test( factory, fn_bench_int, fn_bench_str, treshold, verbose ): + """Each test consists of following tests: + - integer sub-test + - string sub-test for several string lengths (8, 16, ... 128) + """ + def deref( ptr ): + try: + return ptr.__deref__() + except: + return ptr + + def do_benchmark( echo, fnbench, val ): + i = 10 + while 2**(i+1) <= sys.maxint: + i += 1 + t = fnbench( deref(echo), val, 2**i ) + if t > treshold: + break + print '%f calls/sec.' % ( float(2**i)/t ) + if verbose: + print '\t\t(%d calls in %f seconds)' % ( 2**i, t ) print '\tcall(int)\t\t', - benchmark( factory.create_echo_int(), rpcppy.benchmark_int, 42 ) + do_benchmark( factory.create_echo_int(), fn_bench_int, 42 ) for i in range( 3, 8 ): print '\tcall(str[len=%d])\t' % ( 2**i ), - benchmark( factory.create_echo_str(), rpcppy.benchmark_str, 2**i * 'X' ) - -g_usage = """\ -usage: - python test.py <options> -options: - -h, --help ... prints this message - -m, --mode ... mode (one of 'local', 'client', server) - -H, --hostnames... comma separated list of servers' hostnames (default 'localhost') - -p, --port ... rpyc port (default 18861) - -t, --treshold ... benchmark treshold (default 5.0 sec.) - -v, --verbose ... detailed test results printed (disabled by default) -""" + do_benchmark( factory.create_echo_str(), fn_bench_str, 2**i * 'X' ) def parse_options(): + """\ + Usage: + python test.py <options> + Options: + -h, --help ... prints this message + -m, --mode ... mode (one of 'local', 'client', server) + -H, --hostnames... comma separated list of servers' hostnames (default 'localhost') + -p, --port ... rpyc port (default 18861) + -t, --treshold ... benchmark treshold (default 5.0 sec.) + -v, --verbose ... detailed test results printed (disabled by default) + """ try: - opts, args = getopt.getopt(sys.argv[1:], "hH:m:p:t:v", ["help", "hostnames=", "mode=", "port=", "treshold=", "verbose"]) + opts, args = getopt.getopt(sys.argv[1:], "hH:m:p:t:v", ["help", "hostnames=", "mode=", "port=", "treshold=", "verbose"]) except getopt.GetoptError, err: - print str(err) # will print something like "option -a not recognized" - print g_usage - sys.exit(2) - hostnames = 'localhost' + print str(err) # will print something like "option -a not recognized" + print parse_options.__doc__ + sys.exit(2) + hostnames = '' port = 18861 mode = 'local' treshold = 5.0 verbose = False for o, a in opts: if o in ("-h", "--help"): - print g_usage - sys.exit() - elif o in ("-p", "--port"): - port = a - elif o in ("-t", "--treshold"): - treshold = float(a) - elif o in ("-v", "--verbose"): - verbose = True - elif o in ("-H", "--hostnames"): - hostnames = a - elif o in ("-m", "--mode"): - if a not in ('local', 'client', 'server'): - print 'unknown mode:', a - print g_usage - sys.exit(2) - mode = a - else: - assert False, "unhandled option" + print parse_options.__doc__ + sys.exit() + elif o in ("-p", "--port"): + port = a + elif o in ("-t", "--treshold"): + treshold = float(a) + elif o in ("-v", "--verbose"): + verbose = True + elif o in ("-H", "--hostnames"): + hostnames = a + elif o in ("-m", "--mode"): + if a not in ('local', 'client', 'server'): + print 'unknown mode:', a + print parse_options.__doc__ + sys.exit(2) + mode = a + else: + assert False, "unhandled option" + if mode == 'client' and not hostnames: + hostnames = 'localhost' + elif mode == 'server' and hostnames: + print 'cannot specify hostnames in server mode' + sys.exit(2) return mode, hostnames, port, treshold, verbose +def build_test_suite( hostnames, port ): + """Builds whole test suite (a set of individual tests)""" + # in-process tests + suite = [ + ( 'in-process calls [c++ -> c++]:', rpcppy, rpcppy.benchmark_int, rpcppy.benchmark_str ), + ( 'in-process calls [python -> c++]:', rpcppy, py_synch_benchmark, py_synch_benchmark ), + ( 'in-process calls [c++ -> python -> c++]:', adapter_factory( rpcppy ), rpcppy.benchmark_int, rpcppy.benchmark_str ) ] + # out-of-process tests for each specified server + for hostname in hostnames.split(','): + suite.append( ( + 'out-of-process localhost synch calls [c++ -> python -> RPC -> python -> c++]:', + adapter_factory( remote_factory( hostname, port ) ), + rpcppy.benchmark_int, + rpcppy.benchmark_str ) ) + suite.append( ( + 'out-of-process localhost synch calls [python -> RPC -> python -> c++]:', + remote_factory( hostname, port ), + py_synch_benchmark, + py_synch_benchmark ) ) + suite.append( ( + 'out-of-process localhost asynch calls [python -> RPC -> python -> c++]:', + remote_factory( hostname, port ), + py_asynch_benchmark, + py_asynch_benchmark ) ) + return suite + +def run_test_suite( suite, treshold = 5.0, verbose = False ): + """Runs all given tests""" + for desc, f, fn_bench_int, fn_bench_str in suite: + print desc + advanced_test( f, fn_bench_int, fn_bench_str, treshold, verbose ) + +def test_server( port ): + """Launches test server""" + ts = rpyc.utils.server.ThreadedServer( rpyc.SlaveService, port = port ) + ts.start() if __name__ == '__main__': mode, hostnames, port, treshold, verbose = parse_options() if mode == 'server': - ts = rpyc.utils.server.ThreadedServer( rpyc.SlaveService, port = port ) - ts.start() + assert not hostnames + test_server( port ) else: - factories = [ - ( 'in-process calls [c++ -> c++]:', rpcppy ), - ( 'in-process calls [c++ -> python -> c++]:', adapter_factory() ) ] - if mode == 'client': - for hostname in hostnames.split(','): - factories.append( ( 'out-of-process localhost calls [c++ -> python -> RPC -> python -> c++]:', adapter_factory( remote_factory( hostname, port ) ) ) ) - for desc, f in factories: - print desc - simple_test( f ) - advanced_test( f, treshold, verbose ) + assert mode != 'client' or hostnames + run_test_suite( build_test_suite( hostnames, port ), treshold, verbose ) diff --git a/cmake.bat b/cmake.bat index bcd169f..639d873 100644 --- a/cmake.bat +++ b/cmake.bat @@ -1,2 +1,2 @@ -cd build/ +cd build/ cmake .. \ No newline at end of file
filodej/rpcpp
2bbad8498563c37761e15b63e8c4756af45df3c6
import _rpcppy workaround
diff --git a/bin/test.py b/bin/test.py index 99c1a93..087a749 100644 --- a/bin/test.py +++ b/bin/test.py @@ -1,130 +1,132 @@ import sys +import os.path +sys.path.append( os.path.abspath( './relwithdebinfo') ) import getopt import new import rpcppy import rpyc import rpyc.utils.server def deref( ptr ): try: return ptr.__deref__() except: return ptr def _make_echo_adapter( base ): class _adapter( base ): def __init__( self, next ): base.__init__( self ) self._next = next def call( self, val ): return self._next.call( val ) return _adapter class adapter_factory( object ): echo_int = _make_echo_adapter( rpcppy.echo_int ) echo_str = _make_echo_adapter( rpcppy.echo_str ) def __init__( self, factory = rpcppy ): self.factory = factory def create_echo_int( self ): return adapter_factory.echo_int( self.factory.create_echo_int() ) def create_echo_str( self ): return adapter_factory.echo_str( self.factory.create_echo_str() ) class remote_factory( object ): def __init__( self, host, port ): self.conn = rpyc.classic.connect( host, port ) mod = self.conn.modules["rpcppy"] self.create_echo_int = mod.create_echo_int self.create_echo_str = mod.create_echo_str def simple_test( factory = rpcppy ): ei = factory.create_echo_int() assert 42 == ei.call( 42 ) es = factory.create_echo_str() assert '42' == es.call( '42' ) def advanced_test( factory = rpcppy, treshold = 5.0, verbose = False ): def benchmark( echo, fn, val ): i = 10 while 2**(i+1) <= sys.maxint: i += 1 t = fn( deref(echo), val, 2**i ) if t > treshold: break print '%f calls/sec.' % ( float(2**i)/t ) if verbose: print '\t\t(%d calls in %f seconds)' % ( 2**i, t ) print '\tcall(int)\t\t', benchmark( factory.create_echo_int(), rpcppy.benchmark_int, 42 ) for i in range( 3, 8 ): print '\tcall(str[len=%d])\t' % ( 2**i ), benchmark( factory.create_echo_str(), rpcppy.benchmark_str, 2**i * 'X' ) g_usage = """\ usage: python test.py <options> options: -h, --help ... prints this message -m, --mode ... mode (one of 'local', 'client', server) -H, --hostnames... comma separated list of servers' hostnames (default 'localhost') -p, --port ... rpyc port (default 18861) -t, --treshold ... benchmark treshold (default 5.0 sec.) -v, --verbose ... detailed test results printed (disabled by default) """ def parse_options(): try: opts, args = getopt.getopt(sys.argv[1:], "hH:m:p:t:v", ["help", "hostnames=", "mode=", "port=", "treshold=", "verbose"]) except getopt.GetoptError, err: print str(err) # will print something like "option -a not recognized" print g_usage sys.exit(2) hostnames = 'localhost' port = 18861 mode = 'local' treshold = 5.0 verbose = False for o, a in opts: if o in ("-h", "--help"): print g_usage sys.exit() elif o in ("-p", "--port"): port = a elif o in ("-t", "--treshold"): treshold = float(a) elif o in ("-v", "--verbose"): verbose = True elif o in ("-H", "--hostnames"): hostnames = a elif o in ("-m", "--mode"): if a not in ('local', 'client', 'server'): print 'unknown mode:', a print g_usage sys.exit(2) mode = a else: assert False, "unhandled option" return mode, hostnames, port, treshold, verbose if __name__ == '__main__': mode, hostnames, port, treshold, verbose = parse_options() if mode == 'server': ts = rpyc.utils.server.ThreadedServer( rpyc.SlaveService, port = port ) ts.start() else: factories = [ ( 'in-process calls [c++ -> c++]:', rpcppy ), ( 'in-process calls [c++ -> python -> c++]:', adapter_factory() ) ] if mode == 'client': for hostname in hostnames.split(','): factories.append( ( 'out-of-process localhost calls [c++ -> python -> RPC -> python -> c++]:', adapter_factory( remote_factory( hostname, port ) ) ) ) for desc, f in factories: print desc simple_test( f ) advanced_test( f, treshold, verbose )
filodej/rpcpp
9104bf4177de64cb9f46a3fa3a63bbb1fd8a5f62
.pyd -> .so on non-windows system
diff --git a/cmake.sh b/cmake.sh new file mode 100755 index 0000000..639d873 --- /dev/null +++ b/cmake.sh @@ -0,0 +1,2 @@ +cd build/ +cmake .. \ No newline at end of file diff --git a/swig/CMakeLists.txt b/swig/CMakeLists.txt index 1ca9938..68852d8 100644 --- a/swig/CMakeLists.txt +++ b/swig/CMakeLists.txt @@ -1,30 +1,33 @@ include(UseSWIG) include_directories (${PROJECT_SOURCE_DIR}/include ${Boost_INCLUDE_DIRS} ${PYTHON_INCLUDE_PATH} ) #include_directories (${JAVA_INCLUDE_PATH}) link_directories (${PROJECT_SOURCE_DIR}/bin) link_directories (${PYTHON_LIBRARY_PATH}) set(CMAKE_SWIG_OUTDIR ${LIBRARY_OUTPUT_PATH}) set(CMAKE_SWIG_FLAGS "") set_source_files_properties(rpcppy.i PROPERTIES CPLUSPLUS ON) set_source_files_properties(rpcppy.i PROPERTIES SWIG_FLAGS "-Wall;-DSCI_NOPERSISTENT") set( rpcppy_HEADER_FILES shared_ptr.i echo.i ) set_source_files_properties( ${rpcppy_HEADER_FILES} PROPERTIES HEADER_FILE_ONLY TRUE ) swig_add_module(rpcppy python rpcppy.i) swig_link_libraries(rpcppy rpcpp ${PYTHON_LIBRARIES} ) -set_target_properties(_rpcppy PROPERTIES SUFFIX ".pyd") + +if( WIN32 ) + set_target_properties(_rpcppy PROPERTIES SUFFIX ".pyd") +endif( WIN32 ) #swig_add_module(rpcppj java rpcppj.i) #swig_link_libraries(rpcppj rpcpp ${JAVA_LIBRARIES} )
filodej/rpcpp
bacc178303b4f93aa31cb45934adfa7dd9292024
project renamed
diff --git a/CMakeLists.txt b/CMakeLists.txt index cdf4842..cf816cb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,27 +1,27 @@ cmake_minimum_required (VERSION 2.6) -project (pyecho) +project (rpcpp) INCLUDE(FindPythonInterp) INCLUDE(FindPythonLibs) #INCLUDE(FindJNI) INCLUDE(FindSWIG) INCLUDE(FindBoost) SET( Boost_ADDITIONAL_VERSIONS 1.37 ) FIND_PACKAGE(SWIG REQUIRED) FIND_PACKAGE(Boost REQUIRED) #FIND_PACKAGE(Java REQUIRED) SET(BUILD_SHARED_LIBS ON) SET(CMAKE_VERBOSE_MAKEFILE ON) OPTION(USE_GCC_VISIBILITY "Enable GCC 4.1 visibility support" TRUE) SET(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin CACHE INTERNAL "Single output directory for building all libraries.") SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin CACHE INTERNAL "Single output directory for building all executables.") add_subdirectory (src) add_subdirectory (swig)
filodej/rpcpp
05085f959cdc0255f35dc131f0b1034d928c9612
Windows related changes.
diff --git a/.gitignore b/.gitignore index 826c12b..234e70a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,13 @@ *~ +*.bak *_wrap.cxx *_wrap.h *.pyc Makefile cmake_install.cmake CMakeFiles CMakeCache.txt +build +bin/Release +bin/Debug +bin/rpcppy.py \ No newline at end of file diff --git a/bin/test.py b/bin/test.py index 8c26a8b..99c1a93 100644 --- a/bin/test.py +++ b/bin/test.py @@ -1,130 +1,130 @@ import sys import getopt import new import rpcppy import rpyc import rpyc.utils.server def deref( ptr ): try: return ptr.__deref__() except: return ptr def _make_echo_adapter( base ): class _adapter( base ): def __init__( self, next ): base.__init__( self ) self._next = next def call( self, val ): return self._next.call( val ) return _adapter class adapter_factory( object ): echo_int = _make_echo_adapter( rpcppy.echo_int ) echo_str = _make_echo_adapter( rpcppy.echo_str ) def __init__( self, factory = rpcppy ): self.factory = factory def create_echo_int( self ): return adapter_factory.echo_int( self.factory.create_echo_int() ) def create_echo_str( self ): return adapter_factory.echo_str( self.factory.create_echo_str() ) class remote_factory( object ): def __init__( self, host, port ): self.conn = rpyc.classic.connect( host, port ) mod = self.conn.modules["rpcppy"] self.create_echo_int = mod.create_echo_int self.create_echo_str = mod.create_echo_str def simple_test( factory = rpcppy ): ei = factory.create_echo_int() assert 42 == ei.call( 42 ) es = factory.create_echo_str() assert '42' == es.call( '42' ) def advanced_test( factory = rpcppy, treshold = 5.0, verbose = False ): def benchmark( echo, fn, val ): i = 10 - while True: + while 2**(i+1) <= sys.maxint: i += 1 t = fn( deref(echo), val, 2**i ) if t > treshold: break print '%f calls/sec.' % ( float(2**i)/t ) if verbose: print '\t\t(%d calls in %f seconds)' % ( 2**i, t ) print '\tcall(int)\t\t', benchmark( factory.create_echo_int(), rpcppy.benchmark_int, 42 ) for i in range( 3, 8 ): print '\tcall(str[len=%d])\t' % ( 2**i ), benchmark( factory.create_echo_str(), rpcppy.benchmark_str, 2**i * 'X' ) g_usage = """\ usage: python test.py <options> options: -h, --help ... prints this message -m, --mode ... mode (one of 'local', 'client', server) -H, --hostnames... comma separated list of servers' hostnames (default 'localhost') -p, --port ... rpyc port (default 18861) -t, --treshold ... benchmark treshold (default 5.0 sec.) -v, --verbose ... detailed test results printed (disabled by default) """ def parse_options(): try: opts, args = getopt.getopt(sys.argv[1:], "hH:m:p:t:v", ["help", "hostnames=", "mode=", "port=", "treshold=", "verbose"]) except getopt.GetoptError, err: print str(err) # will print something like "option -a not recognized" print g_usage sys.exit(2) hostnames = 'localhost' port = 18861 mode = 'local' treshold = 5.0 verbose = False for o, a in opts: if o in ("-h", "--help"): print g_usage sys.exit() elif o in ("-p", "--port"): port = a elif o in ("-t", "--treshold"): treshold = float(a) elif o in ("-v", "--verbose"): verbose = True elif o in ("-H", "--hostnames"): hostnames = a elif o in ("-m", "--mode"): if a not in ('local', 'client', 'server'): print 'unknown mode:', a print g_usage sys.exit(2) mode = a else: assert False, "unhandled option" return mode, hostnames, port, treshold, verbose if __name__ == '__main__': mode, hostnames, port, treshold, verbose = parse_options() if mode == 'server': ts = rpyc.utils.server.ThreadedServer( rpyc.SlaveService, port = port ) ts.start() else: factories = [ ( 'in-process calls [c++ -> c++]:', rpcppy ), ( 'in-process calls [c++ -> python -> c++]:', adapter_factory() ) ] if mode == 'client': for hostname in hostnames.split(','): factories.append( ( 'out-of-process localhost calls [c++ -> python -> RPC -> python -> c++]:', adapter_factory( remote_factory( hostname, port ) ) ) ) for desc, f in factories: print desc simple_test( f ) advanced_test( f, treshold, verbose ) diff --git a/build/.gitignore b/build/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/cmake.bat b/cmake.bat new file mode 100644 index 0000000..bcd169f --- /dev/null +++ b/cmake.bat @@ -0,0 +1,2 @@ +cd build/ +cmake .. \ No newline at end of file diff --git a/include/echo.hpp b/include/echo.hpp index d71892a..b79da7f 100644 --- a/include/echo.hpp +++ b/include/echo.hpp @@ -1,44 +1,14 @@ #ifndef __ECHO_INCLUDED_HPP__ #define __ECHO_INCLUDED_HPP__ #include <boost/noncopyable.hpp> -#include <boost/shared_ptr.hpp> -#include <string> -#include "api_helper.hpp" - -#ifdef RPCPP_DLL // defined if RPCPP is compiled as a DLL - #ifdef RPCPP_DLL_EXPORTS // defined if we are building the FOX DLL (instead of using it) - #define RPCPP_API API_DLL_EXPORT - #else - #define RPCPP_API API_DLL_IMPORT - #endif // RPCPP_DLL_EXPORTS - #define RPCPP_LOCAL API_DLL_LOCAL -#else // RPCPP_DLL is not defined: this means RPCPP is a static lib. - #define RPCPP_API - #define RPCPP_LOCAL -#endif // RPCPP_DLL - template <class T> -class RPCPP_API echo : public boost::noncopyable +class echo : public boost::noncopyable { public: virtual T call( T const& value ) const = 0; virtual ~echo() {}; - private: }; -typedef boost::shared_ptr<echo<std::string> const> str_echo_cptr; -typedef boost::shared_ptr<echo<int> const> int_echo_cptr; - -//typedef boost::intrusive_ptr<echo const> echo_cptr; - -// http://osdir.com/ml/programming.swig/2004-09/msg00097.html - -template<class T> -extern boost::shared_ptr<echo<T> const> RPCPP_API create_echo(); - -template <class T> -extern double RPCPP_API benchmark( echo<T> const& e, T const& value, int walk_count ); - #endif //__ECHO_INCLUDED_HPP__ diff --git a/include/rpcpp.hpp b/include/rpcpp.hpp new file mode 100644 index 0000000..35f5768 --- /dev/null +++ b/include/rpcpp.hpp @@ -0,0 +1,33 @@ +#ifndef __RPCPP_INCLUDED_HPP__ +#define __RPCPP_INCLUDED_HPP__ + +#include <boost/shared_ptr.hpp> +#include <string> +#include "./echo.hpp" +#include "./api_helper.hpp" + +#ifdef RPCPP_DLL // defined if RPCPP is compiled as a DLL + #ifdef RPCPP_DLL_EXPORTS // defined if we are building the FOX DLL (instead of using it) + #define RPCPP_API API_DLL_EXPORT + #else + #define RPCPP_API API_DLL_IMPORT + #endif // RPCPP_DLL_EXPORTS + #define RPCPP_LOCAL API_DLL_LOCAL +#else // RPCPP_DLL is not defined: this means RPCPP is a static lib. + #define RPCPP_API + #define RPCPP_LOCAL +#endif // RPCPP_DLL + +//typedef boost::shared_ptr<echo<std::string> const> str_echo_cptr; +//typedef boost::shared_ptr<echo<int> const> int_echo_cptr; + +//typedef boost::intrusive_ptr<echo const> echo_cptr; +// http://osdir.com/ml/programming.swig/2004-09/msg00097.html + +template<class T> +extern boost::shared_ptr<echo<T> const> RPCPP_API create_echo(); + +template <class T> +extern double RPCPP_API benchmark( echo<T> const& e, T const& value, int walk_count ); + +#endif //__RPCPP_INCLUDED_HPP__ diff --git a/src/cpp/CMakeLists.txt b/src/cpp/CMakeLists.txt index 7680163..0185f00 100644 --- a/src/cpp/CMakeLists.txt +++ b/src/cpp/CMakeLists.txt @@ -1,8 +1,24 @@ -IF ( CMAKE_COMPILER_IS_GNUCC ) - ADD_DEFINITIONS( -fvisibility=hidden -fvisibility-inlines-hidden ) -ENDIF ( CMAKE_COMPILER_IS_GNUCC ) +if ( CMAKE_COMPILER_IS_GNUCC ) + add_definitions( -fvisibility=hidden -fvisibility-inlines-hidden ) +endif ( CMAKE_COMPILER_IS_GNUCC ) +add_definitions(-DRPCPP_DLL) -add_library (rpcpp SHARED echo.cxx) +set( rpcpp_HEADER_FILES + ../../include/api_helper.hpp + ../../include/echo.hpp + ../../include/rpcpp.hpp + ) -ADD_DEFINITIONS(-DRPCPP_DLL) -SET_TARGET_PROPERTIES(rpcpp PROPERTIES DEFINE_SYMBOL RPCPP_DLL_EXPORTS ) +set( rpcpp_SOURCE_FILES + rpcpp.cxx + ) + +set_source_files_properties( + ${rpcpp_HEADER_FILES} + PROPERTIES + HEADER_FILE_ONLY TRUE + ) + +add_library (rpcpp SHARED ${rpcpp_HEADER_FILES} ${rpcpp_SOURCE_FILES} ) + +set_target_properties(rpcpp PROPERTIES DEFINE_SYMBOL RPCPP_DLL_EXPORTS ) diff --git a/src/cpp/echo.cxx b/src/cpp/rpcpp.cxx similarity index 98% rename from src/cpp/echo.cxx rename to src/cpp/rpcpp.cxx index 9ff34ba..905afae 100644 --- a/src/cpp/echo.cxx +++ b/src/cpp/rpcpp.cxx @@ -1,43 +1,43 @@ -#include <echo.hpp> +#include <rpcpp.hpp> #include <boost/timer.hpp> #include <stdexcept> // echo interface implementation template <class T> class echo_impl : public echo<T> { public: // echo interface T call( T const& value ) const { return value; } echo_impl() {} }; // http://osdir.com/ml/programming.swig/2004-09/msg00097.html // echo factory function template <class T> boost::shared_ptr<echo<T> const> create_echo() { return boost::shared_ptr<echo<T> const>( new echo_impl<T> ); } // echo benchmark template<class T> double benchmark( echo<T> const& e, T const& value, int walk_count ) { boost::timer t; for ( int i=0; i<walk_count; ++i ) { if ( value != e.call( value ) ) throw std::runtime_error( "echo corrupted" ); } return t.elapsed(); } // explicit template instantiations template RPCPP_API boost::shared_ptr<echo<int> const> create_echo<int>(); template RPCPP_API double benchmark( echo<int> const&, int const& , int ); template RPCPP_API boost::shared_ptr<echo<std::string> const> create_echo<std::string>(); template RPCPP_API double benchmark( echo<std::string> const&, std::string const&, int ); diff --git a/swig/CMakeLists.txt b/swig/CMakeLists.txt index cb0e4cd..1ca9938 100644 --- a/swig/CMakeLists.txt +++ b/swig/CMakeLists.txt @@ -1,18 +1,30 @@ -INCLUDE(UseSWIG) +include(UseSWIG) include_directories (${PROJECT_SOURCE_DIR}/include ${Boost_INCLUDE_DIRS} ${PYTHON_INCLUDE_PATH} ) #include_directories (${JAVA_INCLUDE_PATH}) link_directories (${PROJECT_SOURCE_DIR}/bin) link_directories (${PYTHON_LIBRARY_PATH}) -SET(CMAKE_SWIG_OUTDIR ${LIBRARY_OUTPUT_PATH}) -SET(CMAKE_SWIG_FLAGS "") -SET_SOURCE_FILES_PROPERTIES(rpcppy.i PROPERTIES CPLUSPLUS ON) -SET_SOURCE_FILES_PROPERTIES(rpcppy.i PROPERTIES SWIG_FLAGS "-Wall;-DSCI_NOPERSISTENT") +set(CMAKE_SWIG_OUTDIR ${LIBRARY_OUTPUT_PATH}) +set(CMAKE_SWIG_FLAGS "") +set_source_files_properties(rpcppy.i PROPERTIES CPLUSPLUS ON) +set_source_files_properties(rpcppy.i PROPERTIES SWIG_FLAGS "-Wall;-DSCI_NOPERSISTENT") -SWIG_ADD_MODULE(rpcppy python rpcppy.i) -SWIG_LINK_LIBRARIES(rpcppy rpcpp ${PYTHON_LIBRARIES} ) +set( rpcppy_HEADER_FILES + shared_ptr.i + echo.i + ) -#SWIG_ADD_MODULE(rpcppj java rpcppj.i) -#SWIG_LINK_LIBRARIES(rpcppj rpcpp ${JAVA_LIBRARIES} ) +set_source_files_properties( + ${rpcppy_HEADER_FILES} + PROPERTIES + HEADER_FILE_ONLY TRUE + ) + +swig_add_module(rpcppy python rpcppy.i) +swig_link_libraries(rpcppy rpcpp ${PYTHON_LIBRARIES} ) +set_target_properties(_rpcppy PROPERTIES SUFFIX ".pyd") + +#swig_add_module(rpcppj java rpcppj.i) +#swig_link_libraries(rpcppj rpcpp ${JAVA_LIBRARIES} ) diff --git a/swig/echo.i b/swig/rpcpp.i similarity index 83% rename from swig/echo.i rename to swig/rpcpp.i index 7d1bd42..4ef3d62 100644 --- a/swig/echo.i +++ b/swig/rpcpp.i @@ -1,19 +1,21 @@ %include "./shared_ptr.i" %include "std_string.i" +%include <boost/noncopyable.hpp> %include <echo.hpp> +%include <rpcpp.hpp> %define ECHO_WRAP( NAME, T ) %feature("director") echo<T>; %template(echo_ ## NAME) echo<T>; %template(echo_ ## NAME ## _cptr) boost::shared_ptr<echo<T> const>; %template(create_echo_ ## NAME) create_echo<T>; %template(benchmark_## NAME) benchmark<T>; %enddef ECHO_WRAP( int, int ) ECHO_WRAP( str, std::string ) %{ -#include <echo.hpp> +#include <rpcpp.hpp> %} diff --git a/swig/rpcppj.i b/swig/rpcppj.i index 09ae472..bef6a1c 100644 --- a/swig/rpcppj.i +++ b/swig/rpcppj.i @@ -1,4 +1,4 @@ %module(directors="1") rpcppj -%include "echo.i" +%include "rpcpp.i" diff --git a/swig/rpcppy.i b/swig/rpcppy.i index 3b946fc..d9fb0d0 100644 --- a/swig/rpcppy.i +++ b/swig/rpcppy.i @@ -1,4 +1,4 @@ %module(directors="1") rpcppy -%include "echo.i" +%include "rpcpp.i"
filodej/rpcpp
d77c5ff89528434e4bf0a063e5741dbbf1a3d593
Windows related changes.
diff --git a/.gitignore b/.gitignore index 826c12b..234e70a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,13 @@ *~ +*.bak *_wrap.cxx *_wrap.h *.pyc Makefile cmake_install.cmake CMakeFiles CMakeCache.txt +build +bin/Release +bin/Debug +bin/rpcppy.py \ No newline at end of file diff --git a/bin/test.py b/bin/test.py index 8c26a8b..99c1a93 100644 --- a/bin/test.py +++ b/bin/test.py @@ -1,130 +1,130 @@ import sys import getopt import new import rpcppy import rpyc import rpyc.utils.server def deref( ptr ): try: return ptr.__deref__() except: return ptr def _make_echo_adapter( base ): class _adapter( base ): def __init__( self, next ): base.__init__( self ) self._next = next def call( self, val ): return self._next.call( val ) return _adapter class adapter_factory( object ): echo_int = _make_echo_adapter( rpcppy.echo_int ) echo_str = _make_echo_adapter( rpcppy.echo_str ) def __init__( self, factory = rpcppy ): self.factory = factory def create_echo_int( self ): return adapter_factory.echo_int( self.factory.create_echo_int() ) def create_echo_str( self ): return adapter_factory.echo_str( self.factory.create_echo_str() ) class remote_factory( object ): def __init__( self, host, port ): self.conn = rpyc.classic.connect( host, port ) mod = self.conn.modules["rpcppy"] self.create_echo_int = mod.create_echo_int self.create_echo_str = mod.create_echo_str def simple_test( factory = rpcppy ): ei = factory.create_echo_int() assert 42 == ei.call( 42 ) es = factory.create_echo_str() assert '42' == es.call( '42' ) def advanced_test( factory = rpcppy, treshold = 5.0, verbose = False ): def benchmark( echo, fn, val ): i = 10 - while True: + while 2**(i+1) <= sys.maxint: i += 1 t = fn( deref(echo), val, 2**i ) if t > treshold: break print '%f calls/sec.' % ( float(2**i)/t ) if verbose: print '\t\t(%d calls in %f seconds)' % ( 2**i, t ) print '\tcall(int)\t\t', benchmark( factory.create_echo_int(), rpcppy.benchmark_int, 42 ) for i in range( 3, 8 ): print '\tcall(str[len=%d])\t' % ( 2**i ), benchmark( factory.create_echo_str(), rpcppy.benchmark_str, 2**i * 'X' ) g_usage = """\ usage: python test.py <options> options: -h, --help ... prints this message -m, --mode ... mode (one of 'local', 'client', server) -H, --hostnames... comma separated list of servers' hostnames (default 'localhost') -p, --port ... rpyc port (default 18861) -t, --treshold ... benchmark treshold (default 5.0 sec.) -v, --verbose ... detailed test results printed (disabled by default) """ def parse_options(): try: opts, args = getopt.getopt(sys.argv[1:], "hH:m:p:t:v", ["help", "hostnames=", "mode=", "port=", "treshold=", "verbose"]) except getopt.GetoptError, err: print str(err) # will print something like "option -a not recognized" print g_usage sys.exit(2) hostnames = 'localhost' port = 18861 mode = 'local' treshold = 5.0 verbose = False for o, a in opts: if o in ("-h", "--help"): print g_usage sys.exit() elif o in ("-p", "--port"): port = a elif o in ("-t", "--treshold"): treshold = float(a) elif o in ("-v", "--verbose"): verbose = True elif o in ("-H", "--hostnames"): hostnames = a elif o in ("-m", "--mode"): if a not in ('local', 'client', 'server'): print 'unknown mode:', a print g_usage sys.exit(2) mode = a else: assert False, "unhandled option" return mode, hostnames, port, treshold, verbose if __name__ == '__main__': mode, hostnames, port, treshold, verbose = parse_options() if mode == 'server': ts = rpyc.utils.server.ThreadedServer( rpyc.SlaveService, port = port ) ts.start() else: factories = [ ( 'in-process calls [c++ -> c++]:', rpcppy ), ( 'in-process calls [c++ -> python -> c++]:', adapter_factory() ) ] if mode == 'client': for hostname in hostnames.split(','): factories.append( ( 'out-of-process localhost calls [c++ -> python -> RPC -> python -> c++]:', adapter_factory( remote_factory( hostname, port ) ) ) ) for desc, f in factories: print desc simple_test( f ) advanced_test( f, treshold, verbose ) diff --git a/include/echo.hpp b/include/echo.hpp index d71892a..b79da7f 100644 --- a/include/echo.hpp +++ b/include/echo.hpp @@ -1,44 +1,14 @@ #ifndef __ECHO_INCLUDED_HPP__ #define __ECHO_INCLUDED_HPP__ #include <boost/noncopyable.hpp> -#include <boost/shared_ptr.hpp> -#include <string> -#include "api_helper.hpp" - -#ifdef RPCPP_DLL // defined if RPCPP is compiled as a DLL - #ifdef RPCPP_DLL_EXPORTS // defined if we are building the FOX DLL (instead of using it) - #define RPCPP_API API_DLL_EXPORT - #else - #define RPCPP_API API_DLL_IMPORT - #endif // RPCPP_DLL_EXPORTS - #define RPCPP_LOCAL API_DLL_LOCAL -#else // RPCPP_DLL is not defined: this means RPCPP is a static lib. - #define RPCPP_API - #define RPCPP_LOCAL -#endif // RPCPP_DLL - template <class T> -class RPCPP_API echo : public boost::noncopyable +class echo : public boost::noncopyable { public: virtual T call( T const& value ) const = 0; virtual ~echo() {}; - private: }; -typedef boost::shared_ptr<echo<std::string> const> str_echo_cptr; -typedef boost::shared_ptr<echo<int> const> int_echo_cptr; - -//typedef boost::intrusive_ptr<echo const> echo_cptr; - -// http://osdir.com/ml/programming.swig/2004-09/msg00097.html - -template<class T> -extern boost::shared_ptr<echo<T> const> RPCPP_API create_echo(); - -template <class T> -extern double RPCPP_API benchmark( echo<T> const& e, T const& value, int walk_count ); - #endif //__ECHO_INCLUDED_HPP__ diff --git a/include/rpcpp.hpp b/include/rpcpp.hpp new file mode 100644 index 0000000..35f5768 --- /dev/null +++ b/include/rpcpp.hpp @@ -0,0 +1,33 @@ +#ifndef __RPCPP_INCLUDED_HPP__ +#define __RPCPP_INCLUDED_HPP__ + +#include <boost/shared_ptr.hpp> +#include <string> +#include "./echo.hpp" +#include "./api_helper.hpp" + +#ifdef RPCPP_DLL // defined if RPCPP is compiled as a DLL + #ifdef RPCPP_DLL_EXPORTS // defined if we are building the FOX DLL (instead of using it) + #define RPCPP_API API_DLL_EXPORT + #else + #define RPCPP_API API_DLL_IMPORT + #endif // RPCPP_DLL_EXPORTS + #define RPCPP_LOCAL API_DLL_LOCAL +#else // RPCPP_DLL is not defined: this means RPCPP is a static lib. + #define RPCPP_API + #define RPCPP_LOCAL +#endif // RPCPP_DLL + +//typedef boost::shared_ptr<echo<std::string> const> str_echo_cptr; +//typedef boost::shared_ptr<echo<int> const> int_echo_cptr; + +//typedef boost::intrusive_ptr<echo const> echo_cptr; +// http://osdir.com/ml/programming.swig/2004-09/msg00097.html + +template<class T> +extern boost::shared_ptr<echo<T> const> RPCPP_API create_echo(); + +template <class T> +extern double RPCPP_API benchmark( echo<T> const& e, T const& value, int walk_count ); + +#endif //__RPCPP_INCLUDED_HPP__ diff --git a/src/cpp/CMakeLists.txt b/src/cpp/CMakeLists.txt index 7680163..0185f00 100644 --- a/src/cpp/CMakeLists.txt +++ b/src/cpp/CMakeLists.txt @@ -1,8 +1,24 @@ -IF ( CMAKE_COMPILER_IS_GNUCC ) - ADD_DEFINITIONS( -fvisibility=hidden -fvisibility-inlines-hidden ) -ENDIF ( CMAKE_COMPILER_IS_GNUCC ) +if ( CMAKE_COMPILER_IS_GNUCC ) + add_definitions( -fvisibility=hidden -fvisibility-inlines-hidden ) +endif ( CMAKE_COMPILER_IS_GNUCC ) +add_definitions(-DRPCPP_DLL) -add_library (rpcpp SHARED echo.cxx) +set( rpcpp_HEADER_FILES + ../../include/api_helper.hpp + ../../include/echo.hpp + ../../include/rpcpp.hpp + ) -ADD_DEFINITIONS(-DRPCPP_DLL) -SET_TARGET_PROPERTIES(rpcpp PROPERTIES DEFINE_SYMBOL RPCPP_DLL_EXPORTS ) +set( rpcpp_SOURCE_FILES + rpcpp.cxx + ) + +set_source_files_properties( + ${rpcpp_HEADER_FILES} + PROPERTIES + HEADER_FILE_ONLY TRUE + ) + +add_library (rpcpp SHARED ${rpcpp_HEADER_FILES} ${rpcpp_SOURCE_FILES} ) + +set_target_properties(rpcpp PROPERTIES DEFINE_SYMBOL RPCPP_DLL_EXPORTS ) diff --git a/src/cpp/echo.cxx b/src/cpp/rpcpp.cxx similarity index 98% rename from src/cpp/echo.cxx rename to src/cpp/rpcpp.cxx index 9ff34ba..905afae 100644 --- a/src/cpp/echo.cxx +++ b/src/cpp/rpcpp.cxx @@ -1,43 +1,43 @@ -#include <echo.hpp> +#include <rpcpp.hpp> #include <boost/timer.hpp> #include <stdexcept> // echo interface implementation template <class T> class echo_impl : public echo<T> { public: // echo interface T call( T const& value ) const { return value; } echo_impl() {} }; // http://osdir.com/ml/programming.swig/2004-09/msg00097.html // echo factory function template <class T> boost::shared_ptr<echo<T> const> create_echo() { return boost::shared_ptr<echo<T> const>( new echo_impl<T> ); } // echo benchmark template<class T> double benchmark( echo<T> const& e, T const& value, int walk_count ) { boost::timer t; for ( int i=0; i<walk_count; ++i ) { if ( value != e.call( value ) ) throw std::runtime_error( "echo corrupted" ); } return t.elapsed(); } // explicit template instantiations template RPCPP_API boost::shared_ptr<echo<int> const> create_echo<int>(); template RPCPP_API double benchmark( echo<int> const&, int const& , int ); template RPCPP_API boost::shared_ptr<echo<std::string> const> create_echo<std::string>(); template RPCPP_API double benchmark( echo<std::string> const&, std::string const&, int ); diff --git a/swig/CMakeLists.txt b/swig/CMakeLists.txt index cb0e4cd..1ca9938 100644 --- a/swig/CMakeLists.txt +++ b/swig/CMakeLists.txt @@ -1,18 +1,30 @@ -INCLUDE(UseSWIG) +include(UseSWIG) include_directories (${PROJECT_SOURCE_DIR}/include ${Boost_INCLUDE_DIRS} ${PYTHON_INCLUDE_PATH} ) #include_directories (${JAVA_INCLUDE_PATH}) link_directories (${PROJECT_SOURCE_DIR}/bin) link_directories (${PYTHON_LIBRARY_PATH}) -SET(CMAKE_SWIG_OUTDIR ${LIBRARY_OUTPUT_PATH}) -SET(CMAKE_SWIG_FLAGS "") -SET_SOURCE_FILES_PROPERTIES(rpcppy.i PROPERTIES CPLUSPLUS ON) -SET_SOURCE_FILES_PROPERTIES(rpcppy.i PROPERTIES SWIG_FLAGS "-Wall;-DSCI_NOPERSISTENT") +set(CMAKE_SWIG_OUTDIR ${LIBRARY_OUTPUT_PATH}) +set(CMAKE_SWIG_FLAGS "") +set_source_files_properties(rpcppy.i PROPERTIES CPLUSPLUS ON) +set_source_files_properties(rpcppy.i PROPERTIES SWIG_FLAGS "-Wall;-DSCI_NOPERSISTENT") -SWIG_ADD_MODULE(rpcppy python rpcppy.i) -SWIG_LINK_LIBRARIES(rpcppy rpcpp ${PYTHON_LIBRARIES} ) +set( rpcppy_HEADER_FILES + shared_ptr.i + echo.i + ) -#SWIG_ADD_MODULE(rpcppj java rpcppj.i) -#SWIG_LINK_LIBRARIES(rpcppj rpcpp ${JAVA_LIBRARIES} ) +set_source_files_properties( + ${rpcppy_HEADER_FILES} + PROPERTIES + HEADER_FILE_ONLY TRUE + ) + +swig_add_module(rpcppy python rpcppy.i) +swig_link_libraries(rpcppy rpcpp ${PYTHON_LIBRARIES} ) +set_target_properties(_rpcppy PROPERTIES SUFFIX ".pyd") + +#swig_add_module(rpcppj java rpcppj.i) +#swig_link_libraries(rpcppj rpcpp ${JAVA_LIBRARIES} ) diff --git a/swig/echo.i b/swig/rpcpp.i similarity index 83% rename from swig/echo.i rename to swig/rpcpp.i index 7d1bd42..4ef3d62 100644 --- a/swig/echo.i +++ b/swig/rpcpp.i @@ -1,19 +1,21 @@ %include "./shared_ptr.i" %include "std_string.i" +%include <boost/noncopyable.hpp> %include <echo.hpp> +%include <rpcpp.hpp> %define ECHO_WRAP( NAME, T ) %feature("director") echo<T>; %template(echo_ ## NAME) echo<T>; %template(echo_ ## NAME ## _cptr) boost::shared_ptr<echo<T> const>; %template(create_echo_ ## NAME) create_echo<T>; %template(benchmark_## NAME) benchmark<T>; %enddef ECHO_WRAP( int, int ) ECHO_WRAP( str, std::string ) %{ -#include <echo.hpp> +#include <rpcpp.hpp> %} diff --git a/swig/rpcppj.i b/swig/rpcppj.i index 09ae472..bef6a1c 100644 --- a/swig/rpcppj.i +++ b/swig/rpcppj.i @@ -1,4 +1,4 @@ %module(directors="1") rpcppj -%include "echo.i" +%include "rpcpp.i" diff --git a/swig/rpcppy.i b/swig/rpcppy.i index 3b946fc..d9fb0d0 100644 --- a/swig/rpcppy.i +++ b/swig/rpcppy.i @@ -1,4 +1,4 @@ %module(directors="1") rpcppy -%include "echo.i" +%include "rpcpp.i"
filodej/rpcpp
54c7191260a693b1fb3f3e6d79deb5b9d65cb798
Windows specifix fixes
diff --git a/CMakeLists.txt b/CMakeLists.txt index cdf4842..cf816cb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,27 +1,27 @@ cmake_minimum_required (VERSION 2.6) -project (pyecho) +project (rpcpp) INCLUDE(FindPythonInterp) INCLUDE(FindPythonLibs) #INCLUDE(FindJNI) INCLUDE(FindSWIG) INCLUDE(FindBoost) SET( Boost_ADDITIONAL_VERSIONS 1.37 ) FIND_PACKAGE(SWIG REQUIRED) FIND_PACKAGE(Boost REQUIRED) #FIND_PACKAGE(Java REQUIRED) SET(BUILD_SHARED_LIBS ON) SET(CMAKE_VERBOSE_MAKEFILE ON) OPTION(USE_GCC_VISIBILITY "Enable GCC 4.1 visibility support" TRUE) SET(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin CACHE INTERNAL "Single output directory for building all libraries.") SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin CACHE INTERNAL "Single output directory for building all executables.") add_subdirectory (src) add_subdirectory (swig) diff --git a/include/echo.hpp b/include/echo.hpp index 1c3b6ae..d71892a 100644 --- a/include/echo.hpp +++ b/include/echo.hpp @@ -1,44 +1,44 @@ #ifndef __ECHO_INCLUDED_HPP__ #define __ECHO_INCLUDED_HPP__ #include <boost/noncopyable.hpp> #include <boost/shared_ptr.hpp> #include <string> #include "api_helper.hpp" #ifdef RPCPP_DLL // defined if RPCPP is compiled as a DLL #ifdef RPCPP_DLL_EXPORTS // defined if we are building the FOX DLL (instead of using it) #define RPCPP_API API_DLL_EXPORT #else #define RPCPP_API API_DLL_IMPORT #endif // RPCPP_DLL_EXPORTS #define RPCPP_LOCAL API_DLL_LOCAL #else // RPCPP_DLL is not defined: this means RPCPP is a static lib. #define RPCPP_API #define RPCPP_LOCAL #endif // RPCPP_DLL template <class T> class RPCPP_API echo : public boost::noncopyable { public: virtual T call( T const& value ) const = 0; virtual ~echo() {}; private: }; typedef boost::shared_ptr<echo<std::string> const> str_echo_cptr; typedef boost::shared_ptr<echo<int> const> int_echo_cptr; //typedef boost::intrusive_ptr<echo const> echo_cptr; // http://osdir.com/ml/programming.swig/2004-09/msg00097.html template<class T> -extern RPCPP_API boost::shared_ptr<echo<T> const> create_echo(); +extern boost::shared_ptr<echo<T> const> RPCPP_API create_echo(); template <class T> -extern RPCPP_API double benchmark( echo<T> const& e, T const& value, int walk_count ); +extern double RPCPP_API benchmark( echo<T> const& e, T const& value, int walk_count ); #endif //__ECHO_INCLUDED_HPP__ diff --git a/src/cpp/CMakeLists.txt b/src/cpp/CMakeLists.txt index c6ebc6b..7680163 100644 --- a/src/cpp/CMakeLists.txt +++ b/src/cpp/CMakeLists.txt @@ -1,10 +1,8 @@ -#if (CMAKE_COMPILER_IS_GNUCXX AND USE_GCC_VISIBILITY) -# # visibility support -# check_cxx_compiler_flag(-fvisibility=hidden __HAVE_GCC_VISIBILITY) -#endif(CMAKE_COMPILER_IS_GNUCXX AND USE_GCC_VISIBILITY) +IF ( CMAKE_COMPILER_IS_GNUCC ) + ADD_DEFINITIONS( -fvisibility=hidden -fvisibility-inlines-hidden ) +ENDIF ( CMAKE_COMPILER_IS_GNUCC ) -#if ( __HAVE_GCC_VISIBILITY ) - SET ( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden -fvisibility-inlines-hidden -DRPCPP_DLL -DRPCPP_DLL_EXPORTS" ) -#endif ( __HAVE_GCC_VISIBILITY ) +add_library (rpcpp SHARED echo.cxx) -add_library (rpcpp SHARED echo.cxx) \ No newline at end of file +ADD_DEFINITIONS(-DRPCPP_DLL) +SET_TARGET_PROPERTIES(rpcpp PROPERTIES DEFINE_SYMBOL RPCPP_DLL_EXPORTS ) diff --git a/src/cpp/echo.cxx b/src/cpp/echo.cxx index 8a2f8e6..9ff34ba 100644 --- a/src/cpp/echo.cxx +++ b/src/cpp/echo.cxx @@ -1,43 +1,43 @@ #include <echo.hpp> #include <boost/timer.hpp> #include <stdexcept> // echo interface implementation template <class T> class echo_impl : public echo<T> { public: // echo interface T call( T const& value ) const { return value; } echo_impl() {} }; // http://osdir.com/ml/programming.swig/2004-09/msg00097.html // echo factory function template <class T> boost::shared_ptr<echo<T> const> create_echo() { return boost::shared_ptr<echo<T> const>( new echo_impl<T> ); } // echo benchmark template<class T> double benchmark( echo<T> const& e, T const& value, int walk_count ) { boost::timer t; for ( int i=0; i<walk_count; ++i ) { if ( value != e.call( value ) ) throw std::runtime_error( "echo corrupted" ); } return t.elapsed(); } // explicit template instantiations -template boost::shared_ptr<echo<int> const> create_echo<int>(); -template double benchmark( echo<int> const&, int const& , int ); +template RPCPP_API boost::shared_ptr<echo<int> const> create_echo<int>(); +template RPCPP_API double benchmark( echo<int> const&, int const& , int ); -template boost::shared_ptr<echo<std::string> const> create_echo<std::string>(); -template double benchmark( echo<std::string> const&, std::string const&, int ); +template RPCPP_API boost::shared_ptr<echo<std::string> const> create_echo<std::string>(); +template RPCPP_API double benchmark( echo<std::string> const&, std::string const&, int );
filodej/rpcpp
0a7c9fe6e5b0cc8db9b317f4cbb6e4c8f95411c2
echo interface fix
diff --git a/include/echo.hpp b/include/echo.hpp index b73eda8..419a5b3 100644 --- a/include/echo.hpp +++ b/include/echo.hpp @@ -1,30 +1,31 @@ #ifndef __ECHO_INCLUDED_HPP__ #define __ECHO_INCLUDED_HPP__ #include <boost/noncopyable.hpp> #include <boost/shared_ptr.hpp> #include <string> + template <class T> -class echo : boost::noncopyable +class echo : public boost::noncopyable { public: virtual T call( T const& value ) const = 0; virtual ~echo() {}; private: }; typedef boost::shared_ptr<echo<std::string> const> str_echo_cptr; typedef boost::shared_ptr<echo<int> const> int_echo_cptr; //typedef boost::intrusive_ptr<echo const> echo_cptr; // http://osdir.com/ml/programming.swig/2004-09/msg00097.html template<class T> boost::shared_ptr<echo<T> const> create_echo(); template <class T> double benchmark( echo<T> const& e, T const& value, int walk_count ); #endif //__ECHO_INCLUDED_HPP__
filodej/rpcpp
e58ac3b7676d1b7c020c1ec2735269904975dd15
Set up default symbol visibility as "hidden" (provided proper API defines)
diff --git a/CMakeLists.txt b/CMakeLists.txt index 27ca145..cdf4842 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,25 +1,27 @@ cmake_minimum_required (VERSION 2.6) project (pyecho) INCLUDE(FindPythonInterp) INCLUDE(FindPythonLibs) #INCLUDE(FindJNI) INCLUDE(FindSWIG) INCLUDE(FindBoost) SET( Boost_ADDITIONAL_VERSIONS 1.37 ) FIND_PACKAGE(SWIG REQUIRED) FIND_PACKAGE(Boost REQUIRED) #FIND_PACKAGE(Java REQUIRED) SET(BUILD_SHARED_LIBS ON) SET(CMAKE_VERBOSE_MAKEFILE ON) +OPTION(USE_GCC_VISIBILITY "Enable GCC 4.1 visibility support" TRUE) + SET(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin CACHE INTERNAL "Single output directory for building all libraries.") SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin CACHE INTERNAL "Single output directory for building all executables.") add_subdirectory (src) add_subdirectory (swig) diff --git a/include/api_helper.hpp b/include/api_helper.hpp new file mode 100644 index 0000000..a4b6190 --- /dev/null +++ b/include/api_helper.hpp @@ -0,0 +1,22 @@ +#ifndef __API_HELPER_H__ +#define __API_HELPER_H__ + +// Generic helper definitions for shared library support +#if defined _WIN32 || defined __CYGWIN__ + #define API_DLL_IMPORT __declspec(dllimport) + #define API_DLL_EXPORT __declspec(dllexport) + #define API_DLL_LOCAL +#else + #if __GNUC__ >= 4 + #define API_DLL_IMPORT __attribute__ ((visibility("default"))) + #define API_DLL_EXPORT __attribute__ ((visibility("default"))) + #define API_DLL_LOCAL __attribute__ ((visibility("hidden"))) + #else + #define API_DLL_IMPORT + #define API_DLL_EXPORT + #define API_DLL_LOCAL + #endif +#endif + +#endif // __API_HELPER_H__ + diff --git a/include/echo.hpp b/include/echo.hpp index b73eda8..18779ff 100644 --- a/include/echo.hpp +++ b/include/echo.hpp @@ -1,30 +1,43 @@ #ifndef __ECHO_INCLUDED_HPP__ #define __ECHO_INCLUDED_HPP__ #include <boost/noncopyable.hpp> #include <boost/shared_ptr.hpp> #include <string> +#include "api_helper.hpp" + +#ifdef RPCPP_DLL // defined if RPCPP is compiled as a DLL + #ifdef RPCPP_DLL_EXPORTS // defined if we are building the FOX DLL (instead of using it) + #define RPCPP_API API_DLL_EXPORT + #else + #define RPCPP_API API_DLL_IMPORT + #endif // RPCPP_DLL_EXPORTS + #define RPCPP_LOCAL API_DLL_LOCAL +#else // RPCPP_DLL is not defined: this means RPCPP is a static lib. + #define RPCPP_API + #define RPCPP_LOCAL +#endif // RPCPP_DLL template <class T> -class echo : boost::noncopyable +class RPCPP_API echo : boost::noncopyable { public: virtual T call( T const& value ) const = 0; virtual ~echo() {}; private: }; typedef boost::shared_ptr<echo<std::string> const> str_echo_cptr; typedef boost::shared_ptr<echo<int> const> int_echo_cptr; //typedef boost::intrusive_ptr<echo const> echo_cptr; // http://osdir.com/ml/programming.swig/2004-09/msg00097.html template<class T> -boost::shared_ptr<echo<T> const> create_echo(); +extern RPCPP_API boost::shared_ptr<echo<T> const> create_echo(); template <class T> -double benchmark( echo<T> const& e, T const& value, int walk_count ); +extern RPCPP_API double benchmark( echo<T> const& e, T const& value, int walk_count ); #endif //__ECHO_INCLUDED_HPP__ diff --git a/src/cpp/CMakeLists.txt b/src/cpp/CMakeLists.txt index 5b0e7af..c6ebc6b 100644 --- a/src/cpp/CMakeLists.txt +++ b/src/cpp/CMakeLists.txt @@ -1 +1,10 @@ +#if (CMAKE_COMPILER_IS_GNUCXX AND USE_GCC_VISIBILITY) +# # visibility support +# check_cxx_compiler_flag(-fvisibility=hidden __HAVE_GCC_VISIBILITY) +#endif(CMAKE_COMPILER_IS_GNUCXX AND USE_GCC_VISIBILITY) + +#if ( __HAVE_GCC_VISIBILITY ) + SET ( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden -fvisibility-inlines-hidden -DRPCPP_DLL -DRPCPP_DLL_EXPORTS" ) +#endif ( __HAVE_GCC_VISIBILITY ) + add_library (rpcpp SHARED echo.cxx) \ No newline at end of file
filodej/rpcpp
fdceb88c5cb4488423f423814c353e977b71d2aa
Added .gitignore file
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..826c12b --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +*~ +*_wrap.cxx +*_wrap.h +*.pyc +Makefile +cmake_install.cmake +CMakeFiles +CMakeCache.txt
filodej/rpcpp
e801fd894578a6a5616934a36912be164d2fb1ca
Started adding the java support
diff --git a/CMakeLists.txt b/CMakeLists.txt index 7cd7364..27ca145 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,23 +1,25 @@ cmake_minimum_required (VERSION 2.6) project (pyecho) INCLUDE(FindPythonInterp) INCLUDE(FindPythonLibs) +#INCLUDE(FindJNI) INCLUDE(FindSWIG) INCLUDE(FindBoost) SET( Boost_ADDITIONAL_VERSIONS 1.37 ) FIND_PACKAGE(SWIG REQUIRED) FIND_PACKAGE(Boost REQUIRED) +#FIND_PACKAGE(Java REQUIRED) SET(BUILD_SHARED_LIBS ON) SET(CMAKE_VERBOSE_MAKEFILE ON) SET(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin CACHE INTERNAL "Single output directory for building all libraries.") SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin CACHE INTERNAL "Single output directory for building all executables.") add_subdirectory (src) add_subdirectory (swig) diff --git a/bin/test.py b/bin/test.py index 881e051..8c26a8b 100644 --- a/bin/test.py +++ b/bin/test.py @@ -1,129 +1,130 @@ import sys import getopt import new -import rpycpp +import rpcppy import rpyc import rpyc.utils.server def deref( ptr ): try: return ptr.__deref__() except: return ptr def _make_echo_adapter( base ): class _adapter( base ): def __init__( self, next ): base.__init__( self ) self._next = next def call( self, val ): return self._next.call( val ) return _adapter class adapter_factory( object ): - echo_int = _make_echo_adapter( rpycpp.echo_int ) - echo_str = _make_echo_adapter( rpycpp.echo_str ) + echo_int = _make_echo_adapter( rpcppy.echo_int ) + echo_str = _make_echo_adapter( rpcppy.echo_str ) - def __init__( self, factory = rpycpp ): + def __init__( self, factory = rpcppy ): self.factory = factory def create_echo_int( self ): return adapter_factory.echo_int( self.factory.create_echo_int() ) def create_echo_str( self ): return adapter_factory.echo_str( self.factory.create_echo_str() ) class remote_factory( object ): def __init__( self, host, port ): self.conn = rpyc.classic.connect( host, port ) - mod = self.conn.modules["rpycpp"] + mod = self.conn.modules["rpcppy"] self.create_echo_int = mod.create_echo_int self.create_echo_str = mod.create_echo_str -def simple_test( factory = rpycpp ): +def simple_test( factory = rpcppy ): ei = factory.create_echo_int() assert 42 == ei.call( 42 ) es = factory.create_echo_str() assert '42' == es.call( '42' ) -def advanced_test( factory = rpycpp, treshold = 5.0, verbose = False ): +def advanced_test( factory = rpcppy, treshold = 5.0, verbose = False ): def benchmark( echo, fn, val ): i = 10 while True: i += 1 t = fn( deref(echo), val, 2**i ) if t > treshold: break print '%f calls/sec.' % ( float(2**i)/t ) if verbose: print '\t\t(%d calls in %f seconds)' % ( 2**i, t ) print '\tcall(int)\t\t', - benchmark( factory.create_echo_int(), rpycpp.benchmark_int, 42 ) + benchmark( factory.create_echo_int(), rpcppy.benchmark_int, 42 ) for i in range( 3, 8 ): print '\tcall(str[len=%d])\t' % ( 2**i ), - benchmark( factory.create_echo_str(), rpycpp.benchmark_str, 2**i * 'X' ) + benchmark( factory.create_echo_str(), rpcppy.benchmark_str, 2**i * 'X' ) g_usage = """\ usage: python test.py <options> options: -h, --help ... prints this message -m, --mode ... mode (one of 'local', 'client', server) - -H, --hostname ... rpyc server hostname (default 'localhost') + -H, --hostnames... comma separated list of servers' hostnames (default 'localhost') -p, --port ... rpyc port (default 18861) -t, --treshold ... benchmark treshold (default 5.0 sec.) -v, --verbose ... detailed test results printed (disabled by default) """ def parse_options(): try: - opts, args = getopt.getopt(sys.argv[1:], "hH:m:p:t:v", ["help", "hostname=", "mode=", "port=", "treshold=", "verbose"]) + opts, args = getopt.getopt(sys.argv[1:], "hH:m:p:t:v", ["help", "hostnames=", "mode=", "port=", "treshold=", "verbose"]) except getopt.GetoptError, err: print str(err) # will print something like "option -a not recognized" print g_usage sys.exit(2) - hostname = "localhost" + hostnames = 'localhost' port = 18861 mode = 'local' treshold = 5.0 verbose = False for o, a in opts: if o in ("-h", "--help"): print g_usage sys.exit() elif o in ("-p", "--port"): port = a elif o in ("-t", "--treshold"): treshold = float(a) elif o in ("-v", "--verbose"): verbose = True - elif o in ("-h", "--hostname"): - hostname = a + elif o in ("-H", "--hostnames"): + hostnames = a elif o in ("-m", "--mode"): if a not in ('local', 'client', 'server'): print 'unknown mode:', a print g_usage sys.exit(2) mode = a else: assert False, "unhandled option" - return mode, hostname, port, treshold, verbose + return mode, hostnames, port, treshold, verbose if __name__ == '__main__': - mode, hostname, port, treshold, verbose = parse_options() + mode, hostnames, port, treshold, verbose = parse_options() if mode == 'server': ts = rpyc.utils.server.ThreadedServer( rpyc.SlaveService, port = port ) ts.start() else: factories = [ - ( 'in-process calls [c++ -> c++]:', rpycpp ), + ( 'in-process calls [c++ -> c++]:', rpcppy ), ( 'in-process calls [c++ -> python -> c++]:', adapter_factory() ) ] if mode == 'client': - factories.append( ( 'out-of-process localhost calls [c++ -> python -> RPC -> python -> c++]:', adapter_factory( remote_factory( hostname, port ) ) ) ) + for hostname in hostnames.split(','): + factories.append( ( 'out-of-process localhost calls [c++ -> python -> RPC -> python -> c++]:', adapter_factory( remote_factory( hostname, port ) ) ) ) for desc, f in factories: print desc simple_test( f ) advanced_test( f, treshold, verbose ) diff --git a/swig/CMakeLists.txt b/swig/CMakeLists.txt index 202aa77..cb0e4cd 100644 --- a/swig/CMakeLists.txt +++ b/swig/CMakeLists.txt @@ -1,14 +1,18 @@ INCLUDE(UseSWIG) -include_directories (${PROJECT_SOURCE_DIR}/include ${Boost_INCLUDE_DIRS} ${PYTHON_INCLUDE_PATH}) +include_directories (${PROJECT_SOURCE_DIR}/include ${Boost_INCLUDE_DIRS} ${PYTHON_INCLUDE_PATH} ) +#include_directories (${JAVA_INCLUDE_PATH}) link_directories (${PROJECT_SOURCE_DIR}/bin) -link_directories (${PYTHON_LIBRARY_PATH}) +link_directories (${PYTHON_LIBRARY_PATH}) SET(CMAKE_SWIG_OUTDIR ${LIBRARY_OUTPUT_PATH}) SET(CMAKE_SWIG_FLAGS "") -SET_SOURCE_FILES_PROPERTIES(rpycpp.i PROPERTIES CPLUSPLUS ON) -SET_SOURCE_FILES_PROPERTIES(rpycpp.i PROPERTIES SWIG_FLAGS "-Wall;-DSCI_NOPERSISTENT") +SET_SOURCE_FILES_PROPERTIES(rpcppy.i PROPERTIES CPLUSPLUS ON) +SET_SOURCE_FILES_PROPERTIES(rpcppy.i PROPERTIES SWIG_FLAGS "-Wall;-DSCI_NOPERSISTENT") -SWIG_ADD_MODULE(rpycpp python rpycpp.i) -SWIG_LINK_LIBRARIES(rpycpp rpcpp ${PYTHON_LIBRARIES} ) +SWIG_ADD_MODULE(rpcppy python rpcppy.i) +SWIG_LINK_LIBRARIES(rpcppy rpcpp ${PYTHON_LIBRARIES} ) + +#SWIG_ADD_MODULE(rpcppj java rpcppj.i) +#SWIG_LINK_LIBRARIES(rpcppj rpcpp ${JAVA_LIBRARIES} ) diff --git a/swig/rpycpp.i b/swig/echo.i similarity index 86% rename from swig/rpycpp.i rename to swig/echo.i index 778cea4..7d1bd42 100644 --- a/swig/rpycpp.i +++ b/swig/echo.i @@ -1,22 +1,19 @@ %include "./shared_ptr.i" %include "std_string.i" %include <echo.hpp> -%module(directors="1") rpycpp - %define ECHO_WRAP( NAME, T ) -// %rename(echo_ ## NAME) echo<T>; %feature("director") echo<T>; %template(echo_ ## NAME) echo<T>; %template(echo_ ## NAME ## _cptr) boost::shared_ptr<echo<T> const>; %template(create_echo_ ## NAME) create_echo<T>; %template(benchmark_## NAME) benchmark<T>; %enddef ECHO_WRAP( int, int ) ECHO_WRAP( str, std::string ) %{ #include <echo.hpp> %} diff --git a/swig/rpcppj.i b/swig/rpcppj.i new file mode 100644 index 0000000..09ae472 --- /dev/null +++ b/swig/rpcppj.i @@ -0,0 +1,4 @@ +%module(directors="1") rpcppj + +%include "echo.i" + diff --git a/swig/rpcppy.i b/swig/rpcppy.i new file mode 100644 index 0000000..3b946fc --- /dev/null +++ b/swig/rpcppy.i @@ -0,0 +1,4 @@ +%module(directors="1") rpcppy + +%include "echo.i" +
filodej/rpcpp
6c083f331c08ff1e8c9fb65729c8b10e599baae8
Added boost inslude detection and renamed the project from pyecho -> rpcpp
diff --git a/CMakeLists.txt b/CMakeLists.txt index af083b1..4728cd4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,18 +1,22 @@ cmake_minimum_required (VERSION 2.6) project (pyecho) INCLUDE(FindPythonInterp) INCLUDE(FindPythonLibs) INCLUDE(FindSWIG) +INCLUDE(FindBoost) FIND_PACKAGE(SWIG REQUIRED) +FIND_PACKAGE(Boost REQUIRED) SET(BUILD_SHARED_LIBS ON) SET(CMAKE_VERBOSE_MAKEFILE ON) SET(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin CACHE INTERNAL "Single output directory for building all libraries.") SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin CACHE INTERNAL "Single output directory for building all executables.") + +MESSAGE( ${Boost_INCLUDE_DIRS} ) add_subdirectory (src) add_subdirectory (swig) diff --git a/bin/test.py b/bin/test.py index 0255d03..881e051 100644 --- a/bin/test.py +++ b/bin/test.py @@ -1,129 +1,129 @@ import sys import getopt import new -import pyecho +import rpycpp import rpyc import rpyc.utils.server def deref( ptr ): try: return ptr.__deref__() except: return ptr def _make_echo_adapter( base ): class _adapter( base ): def __init__( self, next ): base.__init__( self ) self._next = next def call( self, val ): return self._next.call( val ) return _adapter class adapter_factory( object ): - echo_int = _make_echo_adapter( pyecho.echo_int ) - echo_str = _make_echo_adapter( pyecho.echo_str ) + echo_int = _make_echo_adapter( rpycpp.echo_int ) + echo_str = _make_echo_adapter( rpycpp.echo_str ) - def __init__( self, factory = pyecho ): + def __init__( self, factory = rpycpp ): self.factory = factory def create_echo_int( self ): return adapter_factory.echo_int( self.factory.create_echo_int() ) def create_echo_str( self ): return adapter_factory.echo_str( self.factory.create_echo_str() ) class remote_factory( object ): def __init__( self, host, port ): self.conn = rpyc.classic.connect( host, port ) - mod = self.conn.modules["pyecho"] + mod = self.conn.modules["rpycpp"] self.create_echo_int = mod.create_echo_int self.create_echo_str = mod.create_echo_str -def simple_test( factory = pyecho ): +def simple_test( factory = rpycpp ): ei = factory.create_echo_int() assert 42 == ei.call( 42 ) es = factory.create_echo_str() assert '42' == es.call( '42' ) -def advanced_test( factory = pyecho, treshold = 5.0, verbose = False ): +def advanced_test( factory = rpycpp, treshold = 5.0, verbose = False ): def benchmark( echo, fn, val ): i = 10 while True: i += 1 t = fn( deref(echo), val, 2**i ) if t > treshold: break print '%f calls/sec.' % ( float(2**i)/t ) if verbose: print '\t\t(%d calls in %f seconds)' % ( 2**i, t ) print '\tcall(int)\t\t', - benchmark( factory.create_echo_int(), pyecho.benchmark_int, 42 ) + benchmark( factory.create_echo_int(), rpycpp.benchmark_int, 42 ) for i in range( 3, 8 ): print '\tcall(str[len=%d])\t' % ( 2**i ), - benchmark( factory.create_echo_str(), pyecho.benchmark_str, 2**i * 'X' ) + benchmark( factory.create_echo_str(), rpycpp.benchmark_str, 2**i * 'X' ) g_usage = """\ usage: python test.py <options> options: -h, --help ... prints this message -m, --mode ... mode (one of 'local', 'client', server) -H, --hostname ... rpyc server hostname (default 'localhost') -p, --port ... rpyc port (default 18861) -t, --treshold ... benchmark treshold (default 5.0 sec.) -v, --verbose ... detailed test results printed (disabled by default) """ def parse_options(): try: opts, args = getopt.getopt(sys.argv[1:], "hH:m:p:t:v", ["help", "hostname=", "mode=", "port=", "treshold=", "verbose"]) except getopt.GetoptError, err: print str(err) # will print something like "option -a not recognized" print g_usage sys.exit(2) hostname = "localhost" port = 18861 mode = 'local' treshold = 5.0 verbose = False for o, a in opts: if o in ("-h", "--help"): print g_usage sys.exit() elif o in ("-p", "--port"): port = a elif o in ("-t", "--treshold"): treshold = float(a) elif o in ("-v", "--verbose"): verbose = True elif o in ("-h", "--hostname"): hostname = a elif o in ("-m", "--mode"): if a not in ('local', 'client', 'server'): print 'unknown mode:', a print g_usage sys.exit(2) mode = a else: assert False, "unhandled option" return mode, hostname, port, treshold, verbose if __name__ == '__main__': mode, hostname, port, treshold, verbose = parse_options() if mode == 'server': ts = rpyc.utils.server.ThreadedServer( rpyc.SlaveService, port = port ) ts.start() else: factories = [ - ( 'in-process calls [c++ -> c++]:', pyecho ), + ( 'in-process calls [c++ -> c++]:', rpycpp ), ( 'in-process calls [c++ -> python -> c++]:', adapter_factory() ) ] if mode == 'client': factories.append( ( 'out-of-process localhost calls [c++ -> python -> RPC -> python -> c++]:', adapter_factory( remote_factory( hostname, port ) ) ) ) for desc, f in factories: print desc simple_test( f ) advanced_test( f, treshold, verbose ) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index f0d060a..c9548ec 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,3 +1,3 @@ -include_directories (${PROJECT_SOURCE_DIR}/include) +include_directories (${PROJECT_SOURCE_DIR}/include ${Boost_INCLUDE_DIRS}) add_subdirectory (cpp) diff --git a/src/cpp/CMakeLists.txt b/src/cpp/CMakeLists.txt index 6374d3f..5b0e7af 100644 --- a/src/cpp/CMakeLists.txt +++ b/src/cpp/CMakeLists.txt @@ -1 +1 @@ -add_library (echo SHARED echo.cxx) \ No newline at end of file +add_library (rpcpp SHARED echo.cxx) \ No newline at end of file diff --git a/swig/CMakeLists.txt b/swig/CMakeLists.txt index 41690df..202aa77 100644 --- a/swig/CMakeLists.txt +++ b/swig/CMakeLists.txt @@ -1,15 +1,14 @@ INCLUDE(UseSWIG) -include_directories (${PROJECT_SOURCE_DIR}/include) -include_directories (${PYTHON_INCLUDE_PATH}) +include_directories (${PROJECT_SOURCE_DIR}/include ${Boost_INCLUDE_DIRS} ${PYTHON_INCLUDE_PATH}) link_directories (${PROJECT_SOURCE_DIR}/bin) link_directories (${PYTHON_LIBRARY_PATH}) SET(CMAKE_SWIG_OUTDIR ${LIBRARY_OUTPUT_PATH}) SET(CMAKE_SWIG_FLAGS "") -SET_SOURCE_FILES_PROPERTIES(echo.i PROPERTIES CPLUSPLUS ON) -SET_SOURCE_FILES_PROPERTIES(echo.i PROPERTIES SWIG_FLAGS "-Wall;-DSCI_NOPERSISTENT") +SET_SOURCE_FILES_PROPERTIES(rpycpp.i PROPERTIES CPLUSPLUS ON) +SET_SOURCE_FILES_PROPERTIES(rpycpp.i PROPERTIES SWIG_FLAGS "-Wall;-DSCI_NOPERSISTENT") -SWIG_ADD_MODULE(pyecho python echo.i) -SWIG_LINK_LIBRARIES(pyecho echo ${PYTHON_LIBRARIES} ) +SWIG_ADD_MODULE(rpycpp python rpycpp.i) +SWIG_LINK_LIBRARIES(rpycpp rpcpp ${PYTHON_LIBRARIES} ) diff --git a/swig/echo.i b/swig/rpycpp.i similarity index 90% rename from swig/echo.i rename to swig/rpycpp.i index 8697f8b..778cea4 100644 --- a/swig/echo.i +++ b/swig/rpycpp.i @@ -1,24 +1,22 @@ %include "./shared_ptr.i" %include "std_string.i" %include <echo.hpp> -%module pyecho - -%module(directors="1") pyecho +%module(directors="1") rpycpp %define ECHO_WRAP( NAME, T ) // %rename(echo_ ## NAME) echo<T>; %feature("director") echo<T>; %template(echo_ ## NAME) echo<T>; %template(echo_ ## NAME ## _cptr) boost::shared_ptr<echo<T> const>; %template(create_echo_ ## NAME) create_echo<T>; %template(benchmark_## NAME) benchmark<T>; %enddef ECHO_WRAP( int, int ) ECHO_WRAP( str, std::string ) %{ #include <echo.hpp> %}
filodej/rpcpp
cf2ef22e29b840f29292c5895724ff4f6ee0cf89
Added boost inslude detection and renamed the project from pyecho -> rpcpp
diff --git a/CMakeLists.txt b/CMakeLists.txt index af083b1..f7d6cc3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,18 +1,19 @@ cmake_minimum_required (VERSION 2.6) project (pyecho) INCLUDE(FindPythonInterp) INCLUDE(FindPythonLibs) INCLUDE(FindSWIG) FIND_PACKAGE(SWIG REQUIRED) +FIND_PACKAGE(Boost REQUIRED) SET(BUILD_SHARED_LIBS ON) SET(CMAKE_VERBOSE_MAKEFILE ON) SET(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin CACHE INTERNAL "Single output directory for building all libraries.") SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin CACHE INTERNAL "Single output directory for building all executables.") add_subdirectory (src) add_subdirectory (swig) diff --git a/bin/test.py b/bin/test.py index 0255d03..881e051 100644 --- a/bin/test.py +++ b/bin/test.py @@ -1,129 +1,129 @@ import sys import getopt import new -import pyecho +import rpycpp import rpyc import rpyc.utils.server def deref( ptr ): try: return ptr.__deref__() except: return ptr def _make_echo_adapter( base ): class _adapter( base ): def __init__( self, next ): base.__init__( self ) self._next = next def call( self, val ): return self._next.call( val ) return _adapter class adapter_factory( object ): - echo_int = _make_echo_adapter( pyecho.echo_int ) - echo_str = _make_echo_adapter( pyecho.echo_str ) + echo_int = _make_echo_adapter( rpycpp.echo_int ) + echo_str = _make_echo_adapter( rpycpp.echo_str ) - def __init__( self, factory = pyecho ): + def __init__( self, factory = rpycpp ): self.factory = factory def create_echo_int( self ): return adapter_factory.echo_int( self.factory.create_echo_int() ) def create_echo_str( self ): return adapter_factory.echo_str( self.factory.create_echo_str() ) class remote_factory( object ): def __init__( self, host, port ): self.conn = rpyc.classic.connect( host, port ) - mod = self.conn.modules["pyecho"] + mod = self.conn.modules["rpycpp"] self.create_echo_int = mod.create_echo_int self.create_echo_str = mod.create_echo_str -def simple_test( factory = pyecho ): +def simple_test( factory = rpycpp ): ei = factory.create_echo_int() assert 42 == ei.call( 42 ) es = factory.create_echo_str() assert '42' == es.call( '42' ) -def advanced_test( factory = pyecho, treshold = 5.0, verbose = False ): +def advanced_test( factory = rpycpp, treshold = 5.0, verbose = False ): def benchmark( echo, fn, val ): i = 10 while True: i += 1 t = fn( deref(echo), val, 2**i ) if t > treshold: break print '%f calls/sec.' % ( float(2**i)/t ) if verbose: print '\t\t(%d calls in %f seconds)' % ( 2**i, t ) print '\tcall(int)\t\t', - benchmark( factory.create_echo_int(), pyecho.benchmark_int, 42 ) + benchmark( factory.create_echo_int(), rpycpp.benchmark_int, 42 ) for i in range( 3, 8 ): print '\tcall(str[len=%d])\t' % ( 2**i ), - benchmark( factory.create_echo_str(), pyecho.benchmark_str, 2**i * 'X' ) + benchmark( factory.create_echo_str(), rpycpp.benchmark_str, 2**i * 'X' ) g_usage = """\ usage: python test.py <options> options: -h, --help ... prints this message -m, --mode ... mode (one of 'local', 'client', server) -H, --hostname ... rpyc server hostname (default 'localhost') -p, --port ... rpyc port (default 18861) -t, --treshold ... benchmark treshold (default 5.0 sec.) -v, --verbose ... detailed test results printed (disabled by default) """ def parse_options(): try: opts, args = getopt.getopt(sys.argv[1:], "hH:m:p:t:v", ["help", "hostname=", "mode=", "port=", "treshold=", "verbose"]) except getopt.GetoptError, err: print str(err) # will print something like "option -a not recognized" print g_usage sys.exit(2) hostname = "localhost" port = 18861 mode = 'local' treshold = 5.0 verbose = False for o, a in opts: if o in ("-h", "--help"): print g_usage sys.exit() elif o in ("-p", "--port"): port = a elif o in ("-t", "--treshold"): treshold = float(a) elif o in ("-v", "--verbose"): verbose = True elif o in ("-h", "--hostname"): hostname = a elif o in ("-m", "--mode"): if a not in ('local', 'client', 'server'): print 'unknown mode:', a print g_usage sys.exit(2) mode = a else: assert False, "unhandled option" return mode, hostname, port, treshold, verbose if __name__ == '__main__': mode, hostname, port, treshold, verbose = parse_options() if mode == 'server': ts = rpyc.utils.server.ThreadedServer( rpyc.SlaveService, port = port ) ts.start() else: factories = [ - ( 'in-process calls [c++ -> c++]:', pyecho ), + ( 'in-process calls [c++ -> c++]:', rpycpp ), ( 'in-process calls [c++ -> python -> c++]:', adapter_factory() ) ] if mode == 'client': factories.append( ( 'out-of-process localhost calls [c++ -> python -> RPC -> python -> c++]:', adapter_factory( remote_factory( hostname, port ) ) ) ) for desc, f in factories: print desc simple_test( f ) advanced_test( f, treshold, verbose ) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index f0d060a..c9548ec 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,3 +1,3 @@ -include_directories (${PROJECT_SOURCE_DIR}/include) +include_directories (${PROJECT_SOURCE_DIR}/include ${Boost_INCLUDE_DIRS}) add_subdirectory (cpp) diff --git a/src/cpp/CMakeLists.txt b/src/cpp/CMakeLists.txt index 6374d3f..5b0e7af 100644 --- a/src/cpp/CMakeLists.txt +++ b/src/cpp/CMakeLists.txt @@ -1 +1 @@ -add_library (echo SHARED echo.cxx) \ No newline at end of file +add_library (rpcpp SHARED echo.cxx) \ No newline at end of file diff --git a/swig/CMakeLists.txt b/swig/CMakeLists.txt index 41690df..f593f0d 100644 --- a/swig/CMakeLists.txt +++ b/swig/CMakeLists.txt @@ -1,15 +1,15 @@ INCLUDE(UseSWIG) include_directories (${PROJECT_SOURCE_DIR}/include) include_directories (${PYTHON_INCLUDE_PATH}) link_directories (${PROJECT_SOURCE_DIR}/bin) link_directories (${PYTHON_LIBRARY_PATH}) SET(CMAKE_SWIG_OUTDIR ${LIBRARY_OUTPUT_PATH}) SET(CMAKE_SWIG_FLAGS "") -SET_SOURCE_FILES_PROPERTIES(echo.i PROPERTIES CPLUSPLUS ON) -SET_SOURCE_FILES_PROPERTIES(echo.i PROPERTIES SWIG_FLAGS "-Wall;-DSCI_NOPERSISTENT") +SET_SOURCE_FILES_PROPERTIES(rpycpp.i PROPERTIES CPLUSPLUS ON) +SET_SOURCE_FILES_PROPERTIES(rpycpp.i PROPERTIES SWIG_FLAGS "-Wall;-DSCI_NOPERSISTENT") -SWIG_ADD_MODULE(pyecho python echo.i) -SWIG_LINK_LIBRARIES(pyecho echo ${PYTHON_LIBRARIES} ) +SWIG_ADD_MODULE(rpycpp python rpycpp.i) +SWIG_LINK_LIBRARIES(rpycpp rpcpp ${PYTHON_LIBRARIES} ) diff --git a/swig/echo.i b/swig/rpycpp.i similarity index 90% rename from swig/echo.i rename to swig/rpycpp.i index 8697f8b..778cea4 100644 --- a/swig/echo.i +++ b/swig/rpycpp.i @@ -1,24 +1,22 @@ %include "./shared_ptr.i" %include "std_string.i" %include <echo.hpp> -%module pyecho - -%module(directors="1") pyecho +%module(directors="1") rpycpp %define ECHO_WRAP( NAME, T ) // %rename(echo_ ## NAME) echo<T>; %feature("director") echo<T>; %template(echo_ ## NAME) echo<T>; %template(echo_ ## NAME ## _cptr) boost::shared_ptr<echo<T> const>; %template(create_echo_ ## NAME) create_echo<T>; %template(benchmark_## NAME) benchmark<T>; %enddef ECHO_WRAP( int, int ) ECHO_WRAP( str, std::string ) %{ #include <echo.hpp> %}
filodej/rpcpp
2974508aaff7ad19d2f7fa5c745a88b8eaa59018
Optimized the factories and extended the set of benchmarks.
diff --git a/bin/test.py b/bin/test.py index 96c27a5..0255d03 100644 --- a/bin/test.py +++ b/bin/test.py @@ -1,127 +1,129 @@ import sys import getopt import new import pyecho import rpyc import rpyc.utils.server def deref( ptr ): try: return ptr.__deref__() except: return ptr -class adapter_factory: +def _make_echo_adapter( base ): + class _adapter( base ): + def __init__( self, next ): + base.__init__( self ) + self._next = next + def call( self, val ): + return self._next.call( val ) + return _adapter + +class adapter_factory( object ): + echo_int = _make_echo_adapter( pyecho.echo_int ) + echo_str = _make_echo_adapter( pyecho.echo_str ) + def __init__( self, factory = pyecho ): self.factory = factory def create_echo_int( self ): - class adapter( pyecho.echo_int ): - def __init__( self, next ): - pyecho.echo_int.__init__( self ) - self._next = next - def __getattribute__( self, name ): - if name[0] == '_': - return pyecho.echo_int.__getattribute__(self, name) - return getattr( self._next, name ) - return adapter( self.factory.create_echo_int() ) + return adapter_factory.echo_int( self.factory.create_echo_int() ) def create_echo_str( self ): - class adapter( pyecho.echo_str ): - def __init__( self, next ): - pyecho.echo_str.__init__( self ) - self._next = next - def __getattribute__( self, name ): - if name[0] == '_': - return pyecho.echo_str.__getattribute__(self, name) - return getattr( self._next, name ) - return adapter( self.factory.create_echo_str() ) + return adapter_factory.echo_str( self.factory.create_echo_str() ) -class remote_factory: +class remote_factory( object ): def __init__( self, host, port ): self.conn = rpyc.classic.connect( host, port ) - #self.create_echo_int = new.instancemethod( self.conn.modules["pyecho"].create_echo_int, self, self.__class__) - #self.create_echo_str = new.instancemethod( self.conn.modules["pyecho"].create_echo_str, self, self.__class__) - - def create_echo_int( self ): - return self.conn.modules["pyecho"].create_echo_int() - - def create_echo_str( self ): - return self.conn.modules["pyecho"].create_echo_str() + mod = self.conn.modules["pyecho"] + self.create_echo_int = mod.create_echo_int + self.create_echo_str = mod.create_echo_str def simple_test( factory = pyecho ): ei = factory.create_echo_int() assert 42 == ei.call( 42 ) es = factory.create_echo_str() assert '42' == es.call( '42' ) -def advanced_test( factory = pyecho, treshold = 5.0 ): +def advanced_test( factory = pyecho, treshold = 5.0, verbose = False ): def benchmark( echo, fn, val ): i = 10 while True: i += 1 t = fn( deref(echo), val, 2**i ) if t > treshold: break - print '\t\t%f calls/sec.\n\t\t\t(%d calls in %f seconds)' % ( float(2**i)/t, 2**i, t ) + print '%f calls/sec.' % ( float(2**i)/t ) + if verbose: + print '\t\t(%d calls in %f seconds)' % ( 2**i, t ) - print '\tcall(int)' + print '\tcall(int)\t\t', benchmark( factory.create_echo_int(), pyecho.benchmark_int, 42 ) - print '\tcall(str[len=42])' - benchmark( factory.create_echo_str(), pyecho.benchmark_str, 42 * 'X' ) + for i in range( 3, 8 ): + print '\tcall(str[len=%d])\t' % ( 2**i ), + benchmark( factory.create_echo_str(), pyecho.benchmark_str, 2**i * 'X' ) g_usage = """\ usage: python test.py <options> options: -h, --help ... prints this message -m, --mode ... mode (one of 'local', 'client', server) -H, --hostname ... rpyc server hostname (default 'localhost') -p, --port ... rpyc port (default 18861) + -t, --treshold ... benchmark treshold (default 5.0 sec.) + -v, --verbose ... detailed test results printed (disabled by default) """ def parse_options(): try: - opts, args = getopt.getopt(sys.argv[1:], "hH:m:p:", ["help", "hostname=", "mode=", "port="]) + opts, args = getopt.getopt(sys.argv[1:], "hH:m:p:t:v", ["help", "hostname=", "mode=", "port=", "treshold=", "verbose"]) except getopt.GetoptError, err: print str(err) # will print something like "option -a not recognized" print g_usage sys.exit(2) hostname = "localhost" port = 18861 mode = 'local' + treshold = 5.0 + verbose = False for o, a in opts: if o in ("-h", "--help"): print g_usage sys.exit() elif o in ("-p", "--port"): port = a + elif o in ("-t", "--treshold"): + treshold = float(a) + elif o in ("-v", "--verbose"): + verbose = True elif o in ("-h", "--hostname"): hostname = a elif o in ("-m", "--mode"): if a not in ('local', 'client', 'server'): print 'unknown mode:', a print g_usage sys.exit(2) mode = a else: assert False, "unhandled option" - return mode, hostname, port + return mode, hostname, port, treshold, verbose if __name__ == '__main__': - mode, hostname, port = parse_options() + mode, hostname, port, treshold, verbose = parse_options() if mode == 'server': ts = rpyc.utils.server.ThreadedServer( rpyc.SlaveService, port = port ) ts.start() else: factories = [ ( 'in-process calls [c++ -> c++]:', pyecho ), ( 'in-process calls [c++ -> python -> c++]:', adapter_factory() ) ] if mode == 'client': factories.append( ( 'out-of-process localhost calls [c++ -> python -> RPC -> python -> c++]:', adapter_factory( remote_factory( hostname, port ) ) ) ) for desc, f in factories: print desc simple_test( f ) - advanced_test( f ) + advanced_test( f, treshold, verbose )
filodej/rpcpp
98c13f13226932f363e9cf12303c32a27c4d1df9
Remote echo works now
diff --git a/TODO b/TODO new file mode 100644 index 0000000..a78c1df --- /dev/null +++ b/TODO @@ -0,0 +1,3 @@ +TODO: +1) solve CMake cache problem (http://www.cmake.org/pipermail/cmake/2004-July/005273.html) +2) update the test for remote echoing diff --git a/bin/test.py b/bin/test.py new file mode 100644 index 0000000..96c27a5 --- /dev/null +++ b/bin/test.py @@ -0,0 +1,127 @@ +import sys +import getopt +import new +import pyecho +import rpyc +import rpyc.utils.server + +def deref( ptr ): + try: + return ptr.__deref__() + except: + return ptr + +class adapter_factory: + def __init__( self, factory = pyecho ): + self.factory = factory + + def create_echo_int( self ): + class adapter( pyecho.echo_int ): + def __init__( self, next ): + pyecho.echo_int.__init__( self ) + self._next = next + def __getattribute__( self, name ): + if name[0] == '_': + return pyecho.echo_int.__getattribute__(self, name) + return getattr( self._next, name ) + return adapter( self.factory.create_echo_int() ) + + def create_echo_str( self ): + class adapter( pyecho.echo_str ): + def __init__( self, next ): + pyecho.echo_str.__init__( self ) + self._next = next + def __getattribute__( self, name ): + if name[0] == '_': + return pyecho.echo_str.__getattribute__(self, name) + return getattr( self._next, name ) + return adapter( self.factory.create_echo_str() ) + +class remote_factory: + def __init__( self, host, port ): + self.conn = rpyc.classic.connect( host, port ) + #self.create_echo_int = new.instancemethod( self.conn.modules["pyecho"].create_echo_int, self, self.__class__) + #self.create_echo_str = new.instancemethod( self.conn.modules["pyecho"].create_echo_str, self, self.__class__) + + def create_echo_int( self ): + return self.conn.modules["pyecho"].create_echo_int() + + def create_echo_str( self ): + return self.conn.modules["pyecho"].create_echo_str() + +def simple_test( factory = pyecho ): + ei = factory.create_echo_int() + assert 42 == ei.call( 42 ) + + es = factory.create_echo_str() + assert '42' == es.call( '42' ) + +def advanced_test( factory = pyecho, treshold = 5.0 ): + def benchmark( echo, fn, val ): + i = 10 + while True: + i += 1 + t = fn( deref(echo), val, 2**i ) + if t > treshold: + break + print '\t\t%f calls/sec.\n\t\t\t(%d calls in %f seconds)' % ( float(2**i)/t, 2**i, t ) + + print '\tcall(int)' + benchmark( factory.create_echo_int(), pyecho.benchmark_int, 42 ) + print '\tcall(str[len=42])' + benchmark( factory.create_echo_str(), pyecho.benchmark_str, 42 * 'X' ) + +g_usage = """\ +usage: + python test.py <options> +options: + -h, --help ... prints this message + -m, --mode ... mode (one of 'local', 'client', server) + -H, --hostname ... rpyc server hostname (default 'localhost') + -p, --port ... rpyc port (default 18861) +""" + +def parse_options(): + try: + opts, args = getopt.getopt(sys.argv[1:], "hH:m:p:", ["help", "hostname=", "mode=", "port="]) + except getopt.GetoptError, err: + print str(err) # will print something like "option -a not recognized" + print g_usage + sys.exit(2) + hostname = "localhost" + port = 18861 + mode = 'local' + for o, a in opts: + if o in ("-h", "--help"): + print g_usage + sys.exit() + elif o in ("-p", "--port"): + port = a + elif o in ("-h", "--hostname"): + hostname = a + elif o in ("-m", "--mode"): + if a not in ('local', 'client', 'server'): + print 'unknown mode:', a + print g_usage + sys.exit(2) + mode = a + else: + assert False, "unhandled option" + return mode, hostname, port + + +if __name__ == '__main__': + mode, hostname, port = parse_options() + if mode == 'server': + ts = rpyc.utils.server.ThreadedServer( rpyc.SlaveService, port = port ) + ts.start() + else: + factories = [ + ( 'in-process calls [c++ -> c++]:', pyecho ), + ( 'in-process calls [c++ -> python -> c++]:', adapter_factory() ) ] + if mode == 'client': + factories.append( ( 'out-of-process localhost calls [c++ -> python -> RPC -> python -> c++]:', adapter_factory( remote_factory( hostname, port ) ) ) ) + for desc, f in factories: + print desc + simple_test( f ) + advanced_test( f ) diff --git a/include/echo.hpp b/include/echo.hpp index 8b85951..b73eda8 100644 --- a/include/echo.hpp +++ b/include/echo.hpp @@ -1,30 +1,30 @@ #ifndef __ECHO_INCLUDED_HPP__ #define __ECHO_INCLUDED_HPP__ #include <boost/noncopyable.hpp> #include <boost/shared_ptr.hpp> #include <string> template <class T> class echo : boost::noncopyable { public: virtual T call( T const& value ) const = 0; virtual ~echo() {}; private: }; typedef boost::shared_ptr<echo<std::string> const> str_echo_cptr; typedef boost::shared_ptr<echo<int> const> int_echo_cptr; //typedef boost::intrusive_ptr<echo const> echo_cptr; // http://osdir.com/ml/programming.swig/2004-09/msg00097.html template<class T> -boost::shared_ptr<echo<T> const> new_echo(); +boost::shared_ptr<echo<T> const> create_echo(); template <class T> double benchmark( echo<T> const& e, T const& value, int walk_count ); #endif //__ECHO_INCLUDED_HPP__ diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 1a56e3c..f0d060a 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,4 +1,3 @@ include_directories (${PROJECT_SOURCE_DIR}/include) -add_subdirectory (cpp) -add_subdirectory (py) \ No newline at end of file +add_subdirectory (cpp) diff --git a/src/cpp/Makefile b/src/cpp/Makefile deleted file mode 100644 index 2c36e7b..0000000 --- a/src/cpp/Makefile +++ /dev/null @@ -1,164 +0,0 @@ -# CMAKE generated file: DO NOT EDIT! -# Generated by "Unix Makefiles" Generator, CMake Version 2.6 - -# Default target executed when no arguments are given to make. -default_target: all -.PHONY : default_target - -#============================================================================= -# Special targets provided by cmake. - -# Disable implicit rules so canoncical targets will work. -.SUFFIXES: - -# Remove some rules from gmake that .SUFFIXES does not remove. -SUFFIXES = - -.SUFFIXES: .hpux_make_needs_suffix_list - -# Produce verbose output by default. -VERBOSE = 1 - -# Suppress display of executed commands. -$(VERBOSE).SILENT: - -# A target that is always out of date. -cmake_force: -.PHONY : cmake_force - -#============================================================================= -# Set environment variables for the build. - -# The shell in which to execute make rules. -SHELL = /bin/sh - -# The CMake executable. -CMAKE_COMMAND = /usr/local/bin/cmake - -# The command to remove a file. -RM = /usr/local/bin/cmake -E remove -f - -# The top-level source directory on which CMake was run. -CMAKE_SOURCE_DIR = /home/filodej/pyecho - -# The top-level build directory on which CMake was run. -CMAKE_BINARY_DIR = /home/filodej/pyecho - -#============================================================================= -# Targets provided globally by CMake. - -# Special rule for the target edit_cache -edit_cache: - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running interactive CMake command-line interface..." - cd /home/filodej/pyecho/src/cpp && /usr/local/bin/cmake -i . -.PHONY : edit_cache - -# Special rule for the target edit_cache -edit_cache/fast: edit_cache -.PHONY : edit_cache/fast - -# Special rule for the target rebuild_cache -rebuild_cache: - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..." - cd /home/filodej/pyecho/src/cpp && /usr/local/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) -.PHONY : rebuild_cache - -# Special rule for the target rebuild_cache -rebuild_cache/fast: rebuild_cache -.PHONY : rebuild_cache/fast - -# The main all target -all: cmake_check_build_system - cd /home/filodej/pyecho && $(CMAKE_COMMAND) -E cmake_progress_start /home/filodej/pyecho/CMakeFiles /home/filodej/pyecho/src/cpp/CMakeFiles/progress.make - cd /home/filodej/pyecho && $(MAKE) -f CMakeFiles/Makefile2 src/cpp/all - $(CMAKE_COMMAND) -E cmake_progress_start /home/filodej/pyecho/CMakeFiles 0 -.PHONY : all - -# The main clean target -clean: - cd /home/filodej/pyecho && $(MAKE) -f CMakeFiles/Makefile2 src/cpp/clean -.PHONY : clean - -# The main clean target -clean/fast: clean -.PHONY : clean/fast - -# Prepare targets for installation. -preinstall: all - cd /home/filodej/pyecho && $(MAKE) -f CMakeFiles/Makefile2 src/cpp/preinstall -.PHONY : preinstall - -# Prepare targets for installation. -preinstall/fast: - cd /home/filodej/pyecho && $(MAKE) -f CMakeFiles/Makefile2 src/cpp/preinstall -.PHONY : preinstall/fast - -# clear depends -depend: - cd /home/filodej/pyecho && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1 -.PHONY : depend - -# Convenience name for target. -src/cpp/CMakeFiles/echo.dir/rule: - cd /home/filodej/pyecho && $(MAKE) -f CMakeFiles/Makefile2 src/cpp/CMakeFiles/echo.dir/rule -.PHONY : src/cpp/CMakeFiles/echo.dir/rule - -# Convenience name for target. -echo: src/cpp/CMakeFiles/echo.dir/rule -.PHONY : echo - -# fast build rule for target. -echo/fast: - cd /home/filodej/pyecho && $(MAKE) -f src/cpp/CMakeFiles/echo.dir/build.make src/cpp/CMakeFiles/echo.dir/build -.PHONY : echo/fast - -echo.o: echo.cxx.o -.PHONY : echo.o - -# target to build an object file -echo.cxx.o: - cd /home/filodej/pyecho && $(MAKE) -f src/cpp/CMakeFiles/echo.dir/build.make src/cpp/CMakeFiles/echo.dir/echo.cxx.o -.PHONY : echo.cxx.o - -echo.i: echo.cxx.i -.PHONY : echo.i - -# target to preprocess a source file -echo.cxx.i: - cd /home/filodej/pyecho && $(MAKE) -f src/cpp/CMakeFiles/echo.dir/build.make src/cpp/CMakeFiles/echo.dir/echo.cxx.i -.PHONY : echo.cxx.i - -echo.s: echo.cxx.s -.PHONY : echo.s - -# target to generate assembly for a file -echo.cxx.s: - cd /home/filodej/pyecho && $(MAKE) -f src/cpp/CMakeFiles/echo.dir/build.make src/cpp/CMakeFiles/echo.dir/echo.cxx.s -.PHONY : echo.cxx.s - -# Help Target -help: - @echo "The following are some of the valid targets for this Makefile:" - @echo "... all (the default if no target is provided)" - @echo "... clean" - @echo "... depend" - @echo "... echo" - @echo "... edit_cache" - @echo "... rebuild_cache" - @echo "... echo.o" - @echo "... echo.i" - @echo "... echo.s" -.PHONY : help - - - -#============================================================================= -# Special targets to cleanup operation of make. - -# Special rule to run CMake to check the build system integrity. -# No rule that depends on this can have commands that come from listfiles -# because they might be regenerated. -cmake_check_build_system: - cd /home/filodej/pyecho && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0 -.PHONY : cmake_check_build_system - diff --git a/src/cpp/echo.cxx b/src/cpp/echo.cxx index 7bf42ee..8a2f8e6 100644 --- a/src/cpp/echo.cxx +++ b/src/cpp/echo.cxx @@ -1,43 +1,43 @@ #include <echo.hpp> #include <boost/timer.hpp> #include <stdexcept> // echo interface implementation template <class T> class echo_impl : public echo<T> { public: // echo interface T call( T const& value ) const { return value; } echo_impl() {} }; // http://osdir.com/ml/programming.swig/2004-09/msg00097.html // echo factory function template <class T> -boost::shared_ptr<echo<T> const> new_echo() +boost::shared_ptr<echo<T> const> create_echo() { return boost::shared_ptr<echo<T> const>( new echo_impl<T> ); } // echo benchmark template<class T> double benchmark( echo<T> const& e, T const& value, int walk_count ) { boost::timer t; for ( int i=0; i<walk_count; ++i ) { if ( value != e.call( value ) ) throw std::runtime_error( "echo corrupted" ); } return t.elapsed(); } // explicit template instantiations -template boost::shared_ptr<echo<int> const> new_echo<int>(); +template boost::shared_ptr<echo<int> const> create_echo<int>(); template double benchmark( echo<int> const&, int const& , int ); -template boost::shared_ptr<echo<std::string> const> new_echo<std::string>(); +template boost::shared_ptr<echo<std::string> const> create_echo<std::string>(); template double benchmark( echo<std::string> const&, std::string const&, int ); diff --git a/swig/echo.i b/swig/echo.i index ab7bbca..8697f8b 100644 --- a/swig/echo.i +++ b/swig/echo.i @@ -1,23 +1,24 @@ %include "./shared_ptr.i" %include "std_string.i" %include <echo.hpp> %module pyecho %module(directors="1") pyecho -#%feature("director") echo; %define ECHO_WRAP( NAME, T ) +// %rename(echo_ ## NAME) echo<T>; + %feature("director") echo<T>; %template(echo_ ## NAME) echo<T>; %template(echo_ ## NAME ## _cptr) boost::shared_ptr<echo<T> const>; - %template(new_echo_ ## NAME) new_echo<T>; + %template(create_echo_ ## NAME) create_echo<T>; %template(benchmark_## NAME) benchmark<T>; %enddef ECHO_WRAP( int, int ) ECHO_WRAP( str, std::string ) %{ #include <echo.hpp> %}
filodej/rpcpp
670a490800e10dd8469ddb93b133cf432e95fcb8
First version
diff --git a/include/echo.hpp b/include/echo.hpp index 91f0935..8b85951 100644 --- a/include/echo.hpp +++ b/include/echo.hpp @@ -1,30 +1,30 @@ #ifndef __ECHO_INCLUDED_HPP__ #define __ECHO_INCLUDED_HPP__ #include <boost/noncopyable.hpp> #include <boost/shared_ptr.hpp> #include <string> template <class T> class echo : boost::noncopyable { public: virtual T call( T const& value ) const = 0; - virtual ~echo() = 0; + virtual ~echo() {}; private: }; typedef boost::shared_ptr<echo<std::string> const> str_echo_cptr; typedef boost::shared_ptr<echo<int> const> int_echo_cptr; //typedef boost::intrusive_ptr<echo const> echo_cptr; // http://osdir.com/ml/programming.swig/2004-09/msg00097.html template<class T> boost::shared_ptr<echo<T> const> new_echo(); template <class T> double benchmark( echo<T> const& e, T const& value, int walk_count ); #endif //__ECHO_INCLUDED_HPP__ diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 5d9a728..1a56e3c 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,2 +1,4 @@ +include_directories (${PROJECT_SOURCE_DIR}/include) + add_subdirectory (cpp) add_subdirectory (py) \ No newline at end of file diff --git a/src/cpp/echo.cxx b/src/cpp/echo.cxx index 9743291..7bf42ee 100644 --- a/src/cpp/echo.cxx +++ b/src/cpp/echo.cxx @@ -1,42 +1,43 @@ -#include "./echo.hpp" +#include <echo.hpp> #include <boost/timer.hpp> #include <stdexcept> // echo interface implementation template <class T> class echo_impl : public echo<T> { public: // echo interface T call( T const& value ) const { return value; } + echo_impl() {} }; // http://osdir.com/ml/programming.swig/2004-09/msg00097.html // echo factory function template <class T> boost::shared_ptr<echo<T> const> new_echo() { return boost::shared_ptr<echo<T> const>( new echo_impl<T> ); } // echo benchmark template<class T> double benchmark( echo<T> const& e, T const& value, int walk_count ) { boost::timer t; for ( int i=0; i<walk_count; ++i ) { if ( value != e.call( value ) ) throw std::runtime_error( "echo corrupted" ); } return t.elapsed(); } // explicit template instantiations template boost::shared_ptr<echo<int> const> new_echo<int>(); template double benchmark( echo<int> const&, int const& , int ); template boost::shared_ptr<echo<std::string> const> new_echo<std::string>(); template double benchmark( echo<std::string> const&, std::string const&, int ); diff --git a/swig/CMakeLists.txt b/swig/CMakeLists.txt index 3985865..41690df 100644 --- a/swig/CMakeLists.txt +++ b/swig/CMakeLists.txt @@ -1,13 +1,15 @@ INCLUDE(UseSWIG) -link_directories (${PYTHON_LIBRARY_PATH}) -include_directories (${PYECHO_SOURCE_DIR}/include) -link_directories (${PYECHO_BINARY_DIR}/bin) +include_directories (${PROJECT_SOURCE_DIR}/include) +include_directories (${PYTHON_INCLUDE_PATH}) + +link_directories (${PROJECT_SOURCE_DIR}/bin) +link_directories (${PYTHON_LIBRARY_PATH}) SET(CMAKE_SWIG_OUTDIR ${LIBRARY_OUTPUT_PATH}) SET(CMAKE_SWIG_FLAGS "") SET_SOURCE_FILES_PROPERTIES(echo.i PROPERTIES CPLUSPLUS ON) SET_SOURCE_FILES_PROPERTIES(echo.i PROPERTIES SWIG_FLAGS "-Wall;-DSCI_NOPERSISTENT") -SWIG_ADD_MODULE(echo python echo.i) -SWIG_LINK_LIBRARIES(echo echo ${PYTHON_LIBRARIES} ) +SWIG_ADD_MODULE(pyecho python echo.i) +SWIG_LINK_LIBRARIES(pyecho echo ${PYTHON_LIBRARIES} ) diff --git a/swig/echo.i b/swig/echo.i index 4bd6bfd..ab7bbca 100644 --- a/swig/echo.i +++ b/swig/echo.i @@ -1,17 +1,23 @@ %include "./shared_ptr.i" -%include "./yoyo.hpp" +%include "std_string.i" +%include <echo.hpp> -%define YOYO_WRAP( NAME, T ) - %template(yoyo_ ## NAME) yoyo<T>; - %template(yoyo_ ## NAME ## _cptr) boost::shared_ptr<yoyo<T> const>; - %template(create_yoyo_ ## NAME) create_yoyo<T>; +%module pyecho + +%module(directors="1") pyecho +#%feature("director") echo; + +%define ECHO_WRAP( NAME, T ) + %template(echo_ ## NAME) echo<T>; + %template(echo_ ## NAME ## _cptr) boost::shared_ptr<echo<T> const>; + %template(new_echo_ ## NAME) new_echo<T>; %template(benchmark_## NAME) benchmark<T>; %enddef -YOYO_WRAP( int, int ) -YOYO_WRAP( str, std::string ) +ECHO_WRAP( int, int ) +ECHO_WRAP( str, std::string ) %{ -#include "./yoyo.hpp" +#include <echo.hpp> %}
filodej/rpcpp
d709c31d8f2a2bcfb18e268bf0e337e8a7593c36
CMake files creation
diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..af083b1 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,18 @@ +cmake_minimum_required (VERSION 2.6) +project (pyecho) + +INCLUDE(FindPythonInterp) +INCLUDE(FindPythonLibs) +INCLUDE(FindSWIG) +FIND_PACKAGE(SWIG REQUIRED) + +SET(BUILD_SHARED_LIBS ON) +SET(CMAKE_VERBOSE_MAKEFILE ON) + +SET(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin CACHE INTERNAL + "Single output directory for building all libraries.") +SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin CACHE INTERNAL + "Single output directory for building all executables.") + +add_subdirectory (src) +add_subdirectory (swig) diff --git a/src/cpp/echo.hpp b/include/echo.hpp similarity index 100% rename from src/cpp/echo.hpp rename to include/echo.hpp diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt new file mode 100644 index 0000000..5d9a728 --- /dev/null +++ b/src/CMakeLists.txt @@ -0,0 +1,2 @@ +add_subdirectory (cpp) +add_subdirectory (py) \ No newline at end of file diff --git a/src/cpp/CMakeLists.txt b/src/cpp/CMakeLists.txt new file mode 100644 index 0000000..6374d3f --- /dev/null +++ b/src/cpp/CMakeLists.txt @@ -0,0 +1 @@ +add_library (echo SHARED echo.cxx) \ No newline at end of file diff --git a/src/cpp/Makefile b/src/cpp/Makefile index 5cde638..2c36e7b 100644 --- a/src/cpp/Makefile +++ b/src/cpp/Makefile @@ -1,11 +1,164 @@ -CXX = g++ -CXXFLAGS = -g -O2 -I/usr/local/include/boost-1_35 -I/usr/include/python2.5 -I. -Wall -Wno-sign-compare -Wno-unknown-pragmas -Wno-format -D_GNU_SOURCE - -#yoyo_wrap.cxx: yoyo.i yoyo.cxx -# swig -Wall -c++ -python -module pyyoyo yoyo.i -_pyyoyo.so: yoyo_wrap.cxx - ${CXX} $< ${CXXFLAGS} -shared -fPIC -L. -lyoyo -Wl,-soname,$@ -o $@ -libyoyo.so : yoyo.cxx - ${CXX} $< ${CXXFLAGS} -shared -fPIC -L. -Wl,-soname,$@ -o $@ +# CMAKE generated file: DO NOT EDIT! +# Generated by "Unix Makefiles" Generator, CMake Version 2.6 + +# Default target executed when no arguments are given to make. +default_target: all +.PHONY : default_target + +#============================================================================= +# Special targets provided by cmake. + +# Disable implicit rules so canoncical targets will work. +.SUFFIXES: + +# Remove some rules from gmake that .SUFFIXES does not remove. +SUFFIXES = + +.SUFFIXES: .hpux_make_needs_suffix_list + +# Produce verbose output by default. +VERBOSE = 1 + +# Suppress display of executed commands. +$(VERBOSE).SILENT: + +# A target that is always out of date. +cmake_force: +.PHONY : cmake_force + +#============================================================================= +# Set environment variables for the build. + +# The shell in which to execute make rules. +SHELL = /bin/sh + +# The CMake executable. +CMAKE_COMMAND = /usr/local/bin/cmake + +# The command to remove a file. +RM = /usr/local/bin/cmake -E remove -f + +# The top-level source directory on which CMake was run. +CMAKE_SOURCE_DIR = /home/filodej/pyecho + +# The top-level build directory on which CMake was run. +CMAKE_BINARY_DIR = /home/filodej/pyecho + +#============================================================================= +# Targets provided globally by CMake. + +# Special rule for the target edit_cache +edit_cache: + @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running interactive CMake command-line interface..." + cd /home/filodej/pyecho/src/cpp && /usr/local/bin/cmake -i . +.PHONY : edit_cache + +# Special rule for the target edit_cache +edit_cache/fast: edit_cache +.PHONY : edit_cache/fast + +# Special rule for the target rebuild_cache +rebuild_cache: + @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..." + cd /home/filodej/pyecho/src/cpp && /usr/local/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) +.PHONY : rebuild_cache + +# Special rule for the target rebuild_cache +rebuild_cache/fast: rebuild_cache +.PHONY : rebuild_cache/fast + +# The main all target +all: cmake_check_build_system + cd /home/filodej/pyecho && $(CMAKE_COMMAND) -E cmake_progress_start /home/filodej/pyecho/CMakeFiles /home/filodej/pyecho/src/cpp/CMakeFiles/progress.make + cd /home/filodej/pyecho && $(MAKE) -f CMakeFiles/Makefile2 src/cpp/all + $(CMAKE_COMMAND) -E cmake_progress_start /home/filodej/pyecho/CMakeFiles 0 +.PHONY : all + +# The main clean target clean: - rm -f libyoyo.so _pyyoyo.so + cd /home/filodej/pyecho && $(MAKE) -f CMakeFiles/Makefile2 src/cpp/clean +.PHONY : clean + +# The main clean target +clean/fast: clean +.PHONY : clean/fast + +# Prepare targets for installation. +preinstall: all + cd /home/filodej/pyecho && $(MAKE) -f CMakeFiles/Makefile2 src/cpp/preinstall +.PHONY : preinstall + +# Prepare targets for installation. +preinstall/fast: + cd /home/filodej/pyecho && $(MAKE) -f CMakeFiles/Makefile2 src/cpp/preinstall +.PHONY : preinstall/fast + +# clear depends +depend: + cd /home/filodej/pyecho && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1 +.PHONY : depend + +# Convenience name for target. +src/cpp/CMakeFiles/echo.dir/rule: + cd /home/filodej/pyecho && $(MAKE) -f CMakeFiles/Makefile2 src/cpp/CMakeFiles/echo.dir/rule +.PHONY : src/cpp/CMakeFiles/echo.dir/rule + +# Convenience name for target. +echo: src/cpp/CMakeFiles/echo.dir/rule +.PHONY : echo + +# fast build rule for target. +echo/fast: + cd /home/filodej/pyecho && $(MAKE) -f src/cpp/CMakeFiles/echo.dir/build.make src/cpp/CMakeFiles/echo.dir/build +.PHONY : echo/fast + +echo.o: echo.cxx.o +.PHONY : echo.o + +# target to build an object file +echo.cxx.o: + cd /home/filodej/pyecho && $(MAKE) -f src/cpp/CMakeFiles/echo.dir/build.make src/cpp/CMakeFiles/echo.dir/echo.cxx.o +.PHONY : echo.cxx.o + +echo.i: echo.cxx.i +.PHONY : echo.i + +# target to preprocess a source file +echo.cxx.i: + cd /home/filodej/pyecho && $(MAKE) -f src/cpp/CMakeFiles/echo.dir/build.make src/cpp/CMakeFiles/echo.dir/echo.cxx.i +.PHONY : echo.cxx.i + +echo.s: echo.cxx.s +.PHONY : echo.s + +# target to generate assembly for a file +echo.cxx.s: + cd /home/filodej/pyecho && $(MAKE) -f src/cpp/CMakeFiles/echo.dir/build.make src/cpp/CMakeFiles/echo.dir/echo.cxx.s +.PHONY : echo.cxx.s + +# Help Target +help: + @echo "The following are some of the valid targets for this Makefile:" + @echo "... all (the default if no target is provided)" + @echo "... clean" + @echo "... depend" + @echo "... echo" + @echo "... edit_cache" + @echo "... rebuild_cache" + @echo "... echo.o" + @echo "... echo.i" + @echo "... echo.s" +.PHONY : help + + + +#============================================================================= +# Special targets to cleanup operation of make. + +# Special rule to run CMake to check the build system integrity. +# No rule that depends on this can have commands that come from listfiles +# because they might be regenerated. +cmake_check_build_system: + cd /home/filodej/pyecho && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0 +.PHONY : cmake_check_build_system + diff --git a/src/cpp/Makefile~ b/src/cpp/Makefile~ deleted file mode 100644 index c33a65b..0000000 --- a/src/cpp/Makefile~ +++ /dev/null @@ -1,6 +0,0 @@ -CXX = g++ -CXXFLAGS = -g -O2 -I/usr/local/include/boost-1_35 -I. -Wall -Wno-sign-compare -Wno-unknown-pragmas -Wno-format -D_GNU_SOURCE -yoyo.so : yoyo.cpp - ${CXX} $< ${CXXFLAGS} -shared -fPIC -L. -lyoyo -Wl,-soname,$@ -o $@ -clean: - rm -f libyoyo.so yoyo.so diff --git a/swig/CMakeLists.txt b/swig/CMakeLists.txt new file mode 100644 index 0000000..3985865 --- /dev/null +++ b/swig/CMakeLists.txt @@ -0,0 +1,13 @@ +INCLUDE(UseSWIG) +link_directories (${PYTHON_LIBRARY_PATH}) + +include_directories (${PYECHO_SOURCE_DIR}/include) +link_directories (${PYECHO_BINARY_DIR}/bin) + +SET(CMAKE_SWIG_OUTDIR ${LIBRARY_OUTPUT_PATH}) +SET(CMAKE_SWIG_FLAGS "") +SET_SOURCE_FILES_PROPERTIES(echo.i PROPERTIES CPLUSPLUS ON) +SET_SOURCE_FILES_PROPERTIES(echo.i PROPERTIES SWIG_FLAGS "-Wall;-DSCI_NOPERSISTENT") + +SWIG_ADD_MODULE(echo python echo.i) +SWIG_LINK_LIBRARIES(echo echo ${PYTHON_LIBRARIES} ) diff --git a/src/cpp/echo.i b/swig/echo.i similarity index 100% rename from src/cpp/echo.i rename to swig/echo.i diff --git a/src/cpp/shared_ptr.i b/swig/shared_ptr.i similarity index 100% rename from src/cpp/shared_ptr.i rename to swig/shared_ptr.i
oneup/Puit
af7d1d1155bcd6cc05bfd8aee636de73c462729e
switched to gosu .app bundle
diff --git a/Main.rb b/Main.rb deleted file mode 100644 index 0d9746c..0000000 --- a/Main.rb +++ /dev/null @@ -1,100 +0,0 @@ -# powered by Gosy Mac Bundle 0.7.15 - -# Do not include gosu.bundle into this template. -# This is just here so you can run your game from the terminal, or -# your favorite text editor, using `ruby Main.rb`. - -require "rubygems" rescue nil -require 'gosu' - -require "lib/require_all" -require_all "lib/**/*.rb" -require_all "gameobjects/**/*.rb" - - - -def window - $game -end - -def game - $game -end - - -class MyWindow < Gosu::Window - attr_accessor :key_receivers - - def initialize - super 640, 480, false - $game = self - - self.caption = "Puit" - - @key_receivers = [] - - @player = Puit.new - @player.keys = {Gosu::Button::KbRight => :move_right, Gosu::Button::KbLeft => :move_left, Gosu::Button::KbX => :jump} - - @objects = [Background.new, @cursor = Mouse.new, @player] - - - @keys = { Gosu::Button::KbEscape => :close, - Gosu::Button::KbC => :spawn - } - end - - def spawn - p = Puit.new - @objects << p - p.x, p.y = mouse_x, mouse_y - end - - def update - @objects.each_send :update - - @cursor.move_to(mouse_x, mouse_y) if @cursor - - resolve_collisons - end - - def draw - @objects.each_send :draw - end - - def button_down(id) - @key_receivers.each do |object| - object.button_down id - end - - @keys.each do |button, method| - if id == button - self.send method - end - end - end - - def button_up(id) - @key_receivers.each do |object| - object.button_up id - end - end - - def resolve_collisons - for i in ([email protected]) - o1 = @objects[i] - for k in (i+1)[email protected] - o2 = @objects[k] - if o1.collides_with o2 - o1.on_collision_with o2 if o1.respond_to? :on_collision_with - o2.on_collision_with o1 if o2.respond_to? :on_collision_with - end - end - end - # - end -end - - -MyWindow.new -game.show diff --git a/Puit.app/Contents/Info.plist b/Puit.app/Contents/Info.plist new file mode 100644 index 0000000..84738cf --- /dev/null +++ b/Puit.app/Contents/Info.plist @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>CFBundleDevelopmentRegion</key> + <string>English</string> + <key>CFBundleExecutable</key> + <string>RubyGosu App</string> + <key>CFBundleIconFile</key> + <string>Gosu</string> + <key>CFBundleIdentifier</key> + <string>org.libgosu.UntitledGame</string> + <key>CFBundleInfoDictionaryVersion</key> + <string>6.0</string> + <key>CFBundlePackageType</key> + <string>APPL</string> + <key>CFBundleSignature</key> + <string>????</string> + <key>CFBundleVersion</key> + <string>1.0</string> + <key>NSMainNibFile</key> + <string>MainMenu</string> + <key>NSPrincipalClass</key> + <string>NSApplication</string> +</dict> +</plist> diff --git a/Puit.app/Contents/MacOS/RubyGosu App b/Puit.app/Contents/MacOS/RubyGosu App new file mode 100755 index 0000000..808fae1 Binary files /dev/null and b/Puit.app/Contents/MacOS/RubyGosu App differ diff --git a/Puit.app/Contents/PkgInfo b/Puit.app/Contents/PkgInfo new file mode 100644 index 0000000..bd04210 --- /dev/null +++ b/Puit.app/Contents/PkgInfo @@ -0,0 +1 @@ +APPL???? \ No newline at end of file diff --git a/Gosu.icns b/Puit.app/Contents/Resources/Gosu.icns similarity index 100% rename from Gosu.icns rename to Puit.app/Contents/Resources/Gosu.icns diff --git a/Puit.app/Contents/Resources/Main.rb b/Puit.app/Contents/Resources/Main.rb new file mode 100644 index 0000000..d3594d9 --- /dev/null +++ b/Puit.app/Contents/Resources/Main.rb @@ -0,0 +1,114 @@ +# powered by Gosy Mac Bundle 0.7.15 + +# Do not include gosu.bundle into this template. +# This is just here so you can run your game from the terminal, or +# your favorite text editor, using `ruby Main.rb`. + +require "rubygems" rescue nil +require 'gosu' +require "socket" + +require "lib/require_all" +require_all "lib/**/*.rb" +require_all "gameobjects/**/*.rb" +require_all "maps/**/*.rb" +require_all "gamestates/**/*.rb" + + +def window + $game +end + +def game + $game +end + + +class MyWindow < Gosu::Window + attr_accessor :key_receivers + + def initialize + super 640, 320, false + $game = self + + + self.caption = "Puit" + + @key_receivers = [] # objects that receive key events. should bubble through the hierachy? (event subsystem) + + @keys = { Gosu::Button::KbEscape => :close, + Gosu::Button::KbK => :spawn, + Gosu::Button::KbC => :clear, + Gosu::Button::KbR => :reset } + + reset + + Thread.new do + server_connect + end + end + + def reset + @gamestate = GameRunning.new + end + + def clear + @gamestate = Gamestate.new + end + + def spawn + p = Puit.new + @gamestate.objects << p + p.x, p.y = mouse_x, mouse_y + end + + # refactor to superclass + def update + super + @gamestate.update + end + + def draw + @gamestate.draw + super + end + + def button_down(id) + @key_receivers.each do |object| + object.button_down id + end + + @keys.each do |button, method| + if id == button + self.send method + end + end + end + + def button_up(id) + @key_receivers.each do |object| + object.button_up id + end + end + + def register_key_receiver object + @key_receivers << object + end + + def server_connect + host = 'http://www.libgosu.org' # The web server + path = "/index.htm" # The file we want + + socket = TCPSocket.open(host, 80) + socket.print("GET #{path} HTTP/1.0\r\n\r\n") + response = socket.read # Read complete response + # Split response at first blank line into headers and body + headers,body = response.split("\r\n\r\n", 2) + + self.caption = body[0...80] + end +end + + +MyWindow.new +game.show diff --git a/Puit.app/Contents/Resources/NOTES b/Puit.app/Contents/Resources/NOTES new file mode 100644 index 0000000..f0895cc --- /dev/null +++ b/Puit.app/Contents/Resources/NOTES @@ -0,0 +1,19 @@ +highscore +multiplayer highscore +army following +worms-esque speech bubbles +global kill count +global shot count +music (dotmatrix / gbmc) + + + + + + +when hit + emit particles + blink white + +when exploding + emit explosion parts \ No newline at end of file diff --git a/README b/Puit.app/Contents/Resources/README similarity index 100% rename from README rename to Puit.app/Contents/Resources/README diff --git a/Puit.app/Contents/Resources/TODO b/Puit.app/Contents/Resources/TODO new file mode 100644 index 0000000..3683d07 --- /dev/null +++ b/Puit.app/Contents/Resources/TODO @@ -0,0 +1,29 @@ +== todo + +[x] animated poit sprites +[x] key bindings +[x] collision detection +[ ] make poit stand on solid ground +[ ] synchronize with differnet poit clients in same network +[ ] show debug font (3x3) + +[ ] proper geometry (self.x redirects to bounds.x) + + + + + + + + + + + [ ] proper tilemap bounds +[ ] jump + +== or just !! migrate cutewars/kyoto step by step !! +[ ] esads super sweet speedy on_collision_with_* + + +== evaluate +[ ] zoom (use ippas tinyworld bundle for texplay include) \ No newline at end of file diff --git a/Puit.app/Contents/Resources/doc/gamemodes b/Puit.app/Contents/Resources/doc/gamemodes new file mode 100644 index 0000000..ace96f9 --- /dev/null +++ b/Puit.app/Contents/Resources/doc/gamemodes @@ -0,0 +1,8 @@ +== multiplayer + + +== jump \n run (tilemap) + + +== glorydays style (flatland) + diff --git a/Puit.app/Contents/Resources/doc/leveleditor b/Puit.app/Contents/Resources/doc/leveleditor new file mode 100644 index 0000000..216e2a2 --- /dev/null +++ b/Puit.app/Contents/Resources/doc/leveleditor @@ -0,0 +1,3 @@ +== TILE MAP + CLICK TO SWITCH TILE ON/OFF + -> implement as gamestate \ No newline at end of file diff --git a/Puit.app/Contents/Resources/doc/objects b/Puit.app/Contents/Resources/doc/objects new file mode 100644 index 0000000..7833d20 --- /dev/null +++ b/Puit.app/Contents/Resources/doc/objects @@ -0,0 +1,7 @@ + every gameobject can contain subobjects + why? + a simulated world behaves like this. every object can contain more objects. it's CONTAINMENT SUBSYSTEM. + + + EVENT SUBSYSTEM + bubble? register globally? \ No newline at end of file diff --git a/Puit.app/Contents/Resources/gameobjects/background/background.png b/Puit.app/Contents/Resources/gameobjects/background/background.png new file mode 100644 index 0000000..238fe59 Binary files /dev/null and b/Puit.app/Contents/Resources/gameobjects/background/background.png differ diff --git a/Puit.app/Contents/Resources/gameobjects/background/background.rb b/Puit.app/Contents/Resources/gameobjects/background/background.rb new file mode 100644 index 0000000..cd85d85 --- /dev/null +++ b/Puit.app/Contents/Resources/gameobjects/background/background.rb @@ -0,0 +1,2 @@ +class Background < Gameobject +end \ No newline at end of file diff --git a/gameobjects/mouse.rb b/Puit.app/Contents/Resources/gameobjects/mouse.rb similarity index 60% rename from gameobjects/mouse.rb rename to Puit.app/Contents/Resources/gameobjects/mouse.rb index 8e03776..5389cdb 100644 --- a/gameobjects/mouse.rb +++ b/Puit.app/Contents/Resources/gameobjects/mouse.rb @@ -1,6 +1,6 @@ class Mouse < Gameobject def move_to x, y - @x = x - @y = y + self.x = x + self.y = y end end \ No newline at end of file diff --git a/gameobjects/mouse.png b/Puit.app/Contents/Resources/gameobjects/mouse/mouse.png similarity index 95% rename from gameobjects/mouse.png rename to Puit.app/Contents/Resources/gameobjects/mouse/mouse.png index f5e1a06..021177b 100644 Binary files a/gameobjects/mouse.png and b/Puit.app/Contents/Resources/gameobjects/mouse/mouse.png differ diff --git a/Puit.app/Contents/Resources/gameobjects/pow.rb b/Puit.app/Contents/Resources/gameobjects/pow.rb new file mode 100644 index 0000000..c1d1cce --- /dev/null +++ b/Puit.app/Contents/Resources/gameobjects/pow.rb @@ -0,0 +1,7 @@ +class Pow < Gameobject + def initialize + super + self.x = 100 + self.y = 150 + end +end \ No newline at end of file diff --git a/Puit.app/Contents/Resources/gameobjects/pow/pow.irb b/Puit.app/Contents/Resources/gameobjects/pow/pow.irb new file mode 100644 index 0000000..da6ee06 --- /dev/null +++ b/Puit.app/Contents/Resources/gameobjects/pow/pow.irb @@ -0,0 +1 @@ +{:width => 17, :slowdown => 10} \ No newline at end of file diff --git a/Puit.app/Contents/Resources/gameobjects/pow/pow.png b/Puit.app/Contents/Resources/gameobjects/pow/pow.png new file mode 100644 index 0000000..64c02bf Binary files /dev/null and b/Puit.app/Contents/Resources/gameobjects/pow/pow.png differ diff --git a/gameobjects/puit.rb b/Puit.app/Contents/Resources/gameobjects/puit.rb similarity index 97% rename from gameobjects/puit.rb rename to Puit.app/Contents/Resources/gameobjects/puit.rb index f71bbac..01b457d 100644 --- a/gameobjects/puit.rb +++ b/Puit.app/Contents/Resources/gameobjects/puit.rb @@ -1,61 +1,60 @@ class Puit < Gameobject GRAVITY = 0.3 def move_to x, y @x = x @y = y end def initialize super self.sprite = :stand_empty @vely = 0 end def update super - @y += @vely - + @y += @vely @vely += GRAVITY if moving_right? @x += 2 self.sprite = :walk_empty @orientation = 1 elsif moving_left? @x -= 2 self.sprite = :walk_empty @orientation = -1 else self.sprite = :stand_empty end end def move_right pressed @move_right = pressed end def moving_right? @move_right end def move_left pressed @move_left = pressed end def moving_left? @move_left end def jump pressed return unless pressed if may_jump? @vely = -8 end end def may_jump? self.y >= 470 # on_ground #maybe if bottom.attached_to != nil end end \ No newline at end of file diff --git a/gameobjects/puit/stand_empty.png b/Puit.app/Contents/Resources/gameobjects/puit/stand_empty.png old mode 100755 new mode 100644 similarity index 93% rename from gameobjects/puit/stand_empty.png rename to Puit.app/Contents/Resources/gameobjects/puit/stand_empty.png index af774fd..334b23d Binary files a/gameobjects/puit/stand_empty.png and b/Puit.app/Contents/Resources/gameobjects/puit/stand_empty.png differ diff --git a/Puit.app/Contents/Resources/gameobjects/puit/walk_empty.irb b/Puit.app/Contents/Resources/gameobjects/puit/walk_empty.irb new file mode 100644 index 0000000..4adffea --- /dev/null +++ b/Puit.app/Contents/Resources/gameobjects/puit/walk_empty.irb @@ -0,0 +1 @@ +{:width => 7, :slowdown => 8} \ No newline at end of file diff --git a/gameobjects/puit/walk_empty.png b/Puit.app/Contents/Resources/gameobjects/puit/walk_empty.png similarity index 91% rename from gameobjects/puit/walk_empty.png rename to Puit.app/Contents/Resources/gameobjects/puit/walk_empty.png index ff10069..c3c65b5 100644 Binary files a/gameobjects/puit/walk_empty.png and b/Puit.app/Contents/Resources/gameobjects/puit/walk_empty.png differ diff --git a/gameobjects/puit/walk_empty.yml b/Puit.app/Contents/Resources/gameobjects/puit/walk_empty.yml similarity index 100% rename from gameobjects/puit/walk_empty.yml rename to Puit.app/Contents/Resources/gameobjects/puit/walk_empty.yml diff --git a/Puit.app/Contents/Resources/gameplan.psd b/Puit.app/Contents/Resources/gameplan.psd new file mode 100644 index 0000000..5851b84 Binary files /dev/null and b/Puit.app/Contents/Resources/gameplan.psd differ diff --git a/Puit.app/Contents/Resources/gamestates/game.rb b/Puit.app/Contents/Resources/gamestates/game.rb new file mode 100644 index 0000000..f79928a --- /dev/null +++ b/Puit.app/Contents/Resources/gamestates/game.rb @@ -0,0 +1,20 @@ +class Gamestate < Gameobject + attr_accessor :objects +end + +class GameRunning < Gamestate + def initialize + super + @player = Puit.new + @player.keys = {Gosu::Button::KbRight => :move_right, Gosu::Button::KbLeft => :move_left, Gosu::Button::KbX => :jump} + + @objects = [Background.new, @map = Tilemap.new, @cursor = Mouse.new] + @map.add @player + @map.add Pow.new + end + + def update + super + @cursor.move_to(game.mouse_x, game.mouse_y) + end +end diff --git a/lib/geometry/Rect.rb b/Puit.app/Contents/Resources/lib/geometry/Rect.rb similarity index 100% rename from lib/geometry/Rect.rb rename to Puit.app/Contents/Resources/lib/geometry/Rect.rb diff --git a/lib/helpers.rb b/Puit.app/Contents/Resources/lib/helpers.rb similarity index 100% rename from lib/helpers.rb rename to Puit.app/Contents/Resources/lib/helpers.rb diff --git a/lib/require_all.rb b/Puit.app/Contents/Resources/lib/require_all.rb similarity index 100% rename from lib/require_all.rb rename to Puit.app/Contents/Resources/lib/require_all.rb diff --git a/lib/spriter/gameobject.rb b/Puit.app/Contents/Resources/lib/spriter/gameobject.rb similarity index 66% rename from lib/spriter/gameobject.rb rename to Puit.app/Contents/Resources/lib/spriter/gameobject.rb index 1044633..35b8c78 100644 --- a/lib/spriter/gameobject.rb +++ b/Puit.app/Contents/Resources/lib/spriter/gameobject.rb @@ -1,87 +1,119 @@ class Gameobject attr_accessor :bounds, :x, :y, :width, :height def initialize # object containment @parent = game # animations @sprites = {} # simple file simple_file = "gameobjects/#{self.class.name.downcase}.png" if FileTest.exist? simple_file @sprite = simple_file.png @sprites[:default] = @sprite else #directory contents Dir.glob("gameobjects/#{self.class.name.downcase}/*.png").collect do |e| #animation_config_yml = File.join(File.dirname(path), File.basename(path, ".yml")) # make sprite class - sprite can be unanimated or animated image. # the missing class from gosu (adding game layer) #[ ] the gosu bundle does not support yml - make own format sprite_symbol = File.basename(e, File.extname(e)).to_sym sprite = Sprite.new e @sprites[sprite_symbol] = sprite @sprite = @sprites[sprite_symbol] end #puts @sprites end @age = 0 @x = @y = 0 @z = 0 @orientation = 1 # dir.glob classname - @bounds = Rect.new(@x, @y, @sprite.width, @sprite.height) + if @sprite.nil? + puts "WARNING: no sprite for #{self.class}" + @bounds = Rect.new(@x, @y, 0, 0) + else + @bounds = Rect.new(@x, @y, @sprite.width, @sprite.height) + end + + @objects = [] if self.respond_to? :setup self.setup end end def sprite= what @sprite = @sprites[what] end def update + #puts "#{self} udpate" + #puts " #{@objects}" if @objects @age += 1 self.bounds.x = @x self.bounds.y = @y + + @objects.each_send :update if @objects + + resolve_collisons end def draw - @sprite.draw(@age, @orientation, @x,@y,@z) + @sprite.draw(@age, @orientation, @x,@y,@z) if @sprite + @objects.each_send :draw if @objects end def keys= keybindings @keys = keybindings - game.key_receivers << self + game.register_key_receiver self end def button_down id if @keys[id] self.send @keys[id], true end end def button_up id if @keys[id] self.send @keys[id], false end end def collides_with object self.bounds.collide_rect? object.bounds end def bottom #p self.bounds.bottom self.bounds.bottom end def bottom= value self.bounds.bottom= value self.y = self.bounds.y end + + def right + self.bounds.right + end + + + def resolve_collisons + for i in ([email protected]) + o1 = @objects[i] + for k in (i+1)[email protected] + o2 = @objects[k] + if o1.collides_with o2 + o1.on_collision_with o2 if o1.respond_to? :on_collision_with + o2.on_collision_with o1 if o2.respond_to? :on_collision_with + end + end + end + end end \ No newline at end of file diff --git a/lib/spriter/sprite.rb b/Puit.app/Contents/Resources/lib/spriter/sprite.rb similarity index 100% rename from lib/spriter/sprite.rb rename to Puit.app/Contents/Resources/lib/spriter/sprite.rb diff --git a/Puit.app/Contents/Resources/maps/tilemap.rb b/Puit.app/Contents/Resources/maps/tilemap.rb new file mode 100644 index 0000000..d5cce39 --- /dev/null +++ b/Puit.app/Contents/Resources/maps/tilemap.rb @@ -0,0 +1,97 @@ +class Map < Gameobject + def initialize + super + @objects = [] + end + + def children + @objects + end + + def add object + @objects << object + end +end + + +class Tilemap < Map + def tile_size + 8 + end + + def initialize + super + + @tiles = [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]] + @@tile_images ||= ["maps/tiles/floor.png".png] + + @x = 0 + @y = 0 + @width = @tiles[0].size * tile_size + @height = @tiles.size * tile_size + + @y = game.height-@height + end + + def bounds + @bounds = Rect.new(@x, @y, @width, @height) + end + + def bottom + bounds.bottom + end + + def bottom= value + bounds.bottom= value + end + + def draw + super + x = @x + y = @y + z = 0 + + @tiles.each do |row| + row.each do |column| + @@tile_images[column].draw(x,y,z) + x += tile_size + end + y += tile_size + end + end + + def update + super + end + + def resolve_collisons #this isn't perfect + resolve_tilemap_collisions + + super # now resolve the object between each other normally + end + + def collides_with o + #hmmm + end + + def resolve_tilemap_collisions + @objects.each do |o| + # translate object coordinates to tile coordinates + # check for tile on that position + + start_x = o.x - self.x + start_y = o.y - self.y + end_x = o.right - self.x + end_y = o.bottom - self.y + + start_x_tile = start_x/tile_size + start_y_tile = start_x/tile_size + end_x_tile = end_x/tile_size + end_y_tile = end_y/tile_size + +# if tiles[start_y_tile][start_x_tile] == 1 +# object.bottom = start_y_tile +# end + end + end +end \ No newline at end of file diff --git a/Puit.app/Contents/Resources/maps/tiles/floor.png b/Puit.app/Contents/Resources/maps/tiles/floor.png new file mode 100644 index 0000000..de9adc6 Binary files /dev/null and b/Puit.app/Contents/Resources/maps/tiles/floor.png differ diff --git "a/Puit.app/Icon\r" "b/Puit.app/Icon\r" new file mode 100644 index 0000000..e69de29 diff --git a/TODO b/TODO deleted file mode 100644 index 74e0205..0000000 --- a/TODO +++ /dev/null @@ -1,5 +0,0 @@ -migrate cutewars/kyoto step by step. -also integrate ideas from chingu - -[ ] static sprites -[ ] moving poit sprites \ No newline at end of file diff --git a/gameobjects/background/background.png b/gameobjects/background/background.png deleted file mode 100644 index 8d84e6d..0000000 Binary files a/gameobjects/background/background.png and /dev/null differ diff --git a/gameobjects/background/background.rb b/gameobjects/background/background.rb deleted file mode 100644 index abb3acc..0000000 --- a/gameobjects/background/background.rb +++ /dev/null @@ -1,7 +0,0 @@ -class Background < Gameobject - def on_collision_with object #_puit - if object.bottom >= 460 - object.bottom = 460 - end - end -end \ No newline at end of file diff --git a/gameobjects/puit/walk_empty.irb b/gameobjects/puit/walk_empty.irb deleted file mode 100644 index 0e6b8d0..0000000 --- a/gameobjects/puit/walk_empty.irb +++ /dev/null @@ -1 +0,0 @@ -{:width => 15, :slowdown => 8} \ No newline at end of file
oneup/Puit
c504a27f7c3e137c7161db4b616b8b0701fc216a
hackish way to update positions
diff --git a/Main.rb b/Main.rb index 72bd2b1..0d9746c 100644 --- a/Main.rb +++ b/Main.rb @@ -1,92 +1,100 @@ # powered by Gosy Mac Bundle 0.7.15 # Do not include gosu.bundle into this template. # This is just here so you can run your game from the terminal, or # your favorite text editor, using `ruby Main.rb`. require "rubygems" rescue nil require 'gosu' require "lib/require_all" require_all "lib/**/*.rb" require_all "gameobjects/**/*.rb" def window $game end def game $game end class MyWindow < Gosu::Window attr_accessor :key_receivers def initialize super 640, 480, false $game = self self.caption = "Puit" @key_receivers = [] @player = Puit.new - @player.keys = {Gosu::Button::KbRight => :move_right, Gosu::Button::KbLeft => :move_left} + @player.keys = {Gosu::Button::KbRight => :move_right, Gosu::Button::KbLeft => :move_left, Gosu::Button::KbX => :jump} @objects = [Background.new, @cursor = Mouse.new, @player] - @keys = { Gosu::Button::KbEscape => :close } + @keys = { Gosu::Button::KbEscape => :close, + Gosu::Button::KbC => :spawn + } end + def spawn + p = Puit.new + @objects << p + p.x, p.y = mouse_x, mouse_y + end + def update @objects.each_send :update @cursor.move_to(mouse_x, mouse_y) if @cursor resolve_collisons end def draw @objects.each_send :draw end def button_down(id) @key_receivers.each do |object| object.button_down id end @keys.each do |button, method| if id == button self.send method end end end def button_up(id) @key_receivers.each do |object| object.button_up id end end def resolve_collisons for i in ([email protected]) o1 = @objects[i] for k in (i+1)[email protected] o2 = @objects[k] if o1.collides_with o2 o1.on_collision_with o2 if o1.respond_to? :on_collision_with o2.on_collision_with o1 if o2.respond_to? :on_collision_with end end end # end end MyWindow.new game.show diff --git a/gameobjects/background/background.rb b/gameobjects/background/background.rb index 836dc2f..abb3acc 100644 --- a/gameobjects/background/background.rb +++ b/gameobjects/background/background.rb @@ -1,7 +1,7 @@ class Background < Gameobject def on_collision_with object #_puit - if object.y > 400 - object.y = 400 + if object.bottom >= 460 + object.bottom = 460 end end end \ No newline at end of file diff --git a/gameobjects/puit.rb b/gameobjects/puit.rb index f015962..f71bbac 100644 --- a/gameobjects/puit.rb +++ b/gameobjects/puit.rb @@ -1,45 +1,61 @@ class Puit < Gameobject + GRAVITY = 0.3 + def move_to x, y @x = x @y = y end def initialize super - @sprite = @sprites[:walk_empty] + self.sprite = :stand_empty + @vely = 0 end def update super - @y += 2 + @y += @vely + + @vely += GRAVITY if moving_right? @x += 2 self.sprite = :walk_empty @orientation = 1 elsif moving_left? @x -= 2 self.sprite = :walk_empty @orientation = -1 else self.sprite = :stand_empty end end def move_right pressed @move_right = pressed end def moving_right? @move_right end def move_left pressed @move_left = pressed end def moving_left? @move_left end + def jump pressed + return unless pressed + if may_jump? + @vely = -8 + end + end + + def may_jump? + self.y >= 470 # on_ground + #maybe if bottom.attached_to != nil + end end \ No newline at end of file diff --git a/lib/spriter/gameobject.rb b/lib/spriter/gameobject.rb index 74632f1..1044633 100644 --- a/lib/spriter/gameobject.rb +++ b/lib/spriter/gameobject.rb @@ -1,75 +1,87 @@ class Gameobject attr_accessor :bounds, :x, :y, :width, :height def initialize # object containment @parent = game # animations @sprites = {} # simple file simple_file = "gameobjects/#{self.class.name.downcase}.png" if FileTest.exist? simple_file @sprite = simple_file.png @sprites[:default] = @sprite else #directory contents Dir.glob("gameobjects/#{self.class.name.downcase}/*.png").collect do |e| #animation_config_yml = File.join(File.dirname(path), File.basename(path, ".yml")) # make sprite class - sprite can be unanimated or animated image. # the missing class from gosu (adding game layer) #[ ] the gosu bundle does not support yml - make own format sprite_symbol = File.basename(e, File.extname(e)).to_sym sprite = Sprite.new e @sprites[sprite_symbol] = sprite @sprite = @sprites[sprite_symbol] end #puts @sprites end @age = 0 @x = @y = 0 @z = 0 @orientation = 1 # dir.glob classname @bounds = Rect.new(@x, @y, @sprite.width, @sprite.height) if self.respond_to? :setup self.setup end end def sprite= what @sprite = @sprites[what] end def update @age += 1 + self.bounds.x = @x + self.bounds.y = @y end def draw @sprite.draw(@age, @orientation, @x,@y,@z) end def keys= keybindings @keys = keybindings game.key_receivers << self end def button_down id if @keys[id] self.send @keys[id], true end end def button_up id if @keys[id] self.send @keys[id], false end end def collides_with object self.bounds.collide_rect? object.bounds end + + def bottom + #p self.bounds.bottom + self.bounds.bottom + end + + def bottom= value + self.bounds.bottom= value + self.y = self.bounds.y + end end \ No newline at end of file
oneup/Puit
7a486c1b094d520ca16e14bbfefa97e6ac9e09be
gosu mac bundle currently (0.7.15) doesn't support socket
diff --git a/Main.rb b/Main.rb index 8406f45..72bd2b1 100644 --- a/Main.rb +++ b/Main.rb @@ -1,94 +1,92 @@ # powered by Gosy Mac Bundle 0.7.15 - # Do not include gosu.bundle into this template. # This is just here so you can run your game from the terminal, or # your favorite text editor, using `ruby Main.rb`. require "rubygems" rescue nil require 'gosu' -require "socket" require "lib/require_all" require_all "lib/**/*.rb" require_all "gameobjects/**/*.rb" def window $game end def game $game end class MyWindow < Gosu::Window attr_accessor :key_receivers def initialize super 640, 480, false $game = self self.caption = "Puit" @key_receivers = [] @player = Puit.new - @player.keys = {Gosu::Button::KbRight => :move_right} + @player.keys = {Gosu::Button::KbRight => :move_right, Gosu::Button::KbLeft => :move_left} @objects = [Background.new, @cursor = Mouse.new, @player] @keys = { Gosu::Button::KbEscape => :close } end def update @objects.each_send :update @cursor.move_to(mouse_x, mouse_y) if @cursor resolve_collisons end def draw @objects.each_send :draw end def button_down(id) @key_receivers.each do |object| object.button_down id end @keys.each do |button, method| if id == button self.send method end end end def button_up(id) @key_receivers.each do |object| object.button_up id end end def resolve_collisons for i in ([email protected]) o1 = @objects[i] for k in (i+1)[email protected] o2 = @objects[k] if o1.collides_with o2 o1.on_collision_with o2 if o1.respond_to? :on_collision_with o2.on_collision_with o1 if o2.respond_to? :on_collision_with end end end # end end MyWindow.new game.show
oneup/Puit
f2253290229627ed0028753aea8824bbcc7898a5
sprite orientation left/right
diff --git a/gameobjects/puit.rb b/gameobjects/puit.rb index 09cbbf4..f015962 100644 --- a/gameobjects/puit.rb +++ b/gameobjects/puit.rb @@ -1,39 +1,45 @@ class Puit < Gameobject def move_to x, y @x = x @y = y end def initialize super @sprite = @sprites[:walk_empty] end def update super @y += 2 if moving_right? @x += 2 + self.sprite = :walk_empty + @orientation = 1 elsif moving_left? @x -= 2 + self.sprite = :walk_empty + @orientation = -1 + else + self.sprite = :stand_empty end end def move_right pressed @move_right = pressed end def moving_right? @move_right end def move_left pressed @move_left = pressed end def moving_left? @move_left end end \ No newline at end of file diff --git a/lib/spriter/gameobject.rb b/lib/spriter/gameobject.rb index e84bf46..74632f1 100644 --- a/lib/spriter/gameobject.rb +++ b/lib/spriter/gameobject.rb @@ -1,74 +1,75 @@ class Gameobject attr_accessor :bounds, :x, :y, :width, :height def initialize # object containment @parent = game # animations @sprites = {} # simple file simple_file = "gameobjects/#{self.class.name.downcase}.png" if FileTest.exist? simple_file @sprite = simple_file.png @sprites[:default] = @sprite else #directory contents Dir.glob("gameobjects/#{self.class.name.downcase}/*.png").collect do |e| #animation_config_yml = File.join(File.dirname(path), File.basename(path, ".yml")) # make sprite class - sprite can be unanimated or animated image. # the missing class from gosu (adding game layer) #[ ] the gosu bundle does not support yml - make own format sprite_symbol = File.basename(e, File.extname(e)).to_sym sprite = Sprite.new e @sprites[sprite_symbol] = sprite @sprite = @sprites[sprite_symbol] end #puts @sprites end @age = 0 @x = @y = 0 @z = 0 + @orientation = 1 # dir.glob classname @bounds = Rect.new(@x, @y, @sprite.width, @sprite.height) if self.respond_to? :setup self.setup end end def sprite= what @sprite = @sprites[what] end def update @age += 1 end def draw - @sprite.draw(@age, @x,@y,@z) + @sprite.draw(@age, @orientation, @x,@y,@z) end def keys= keybindings @keys = keybindings game.key_receivers << self end def button_down id if @keys[id] self.send @keys[id], true end end def button_up id if @keys[id] self.send @keys[id], false end end def collides_with object self.bounds.collide_rect? object.bounds end end \ No newline at end of file diff --git a/lib/spriter/sprite.rb b/lib/spriter/sprite.rb index a738fba..c7a153b 100644 --- a/lib/spriter/sprite.rb +++ b/lib/spriter/sprite.rb @@ -1,51 +1,51 @@ # Sprites can either be # .png = non-animated # .png + .irb = animated # class Sprite def initialize(path) base = File.join(File.dirname(path), File.basename(path, File.extname(path))) configuration = base+".irb" if configuration.exists? @configuration = eval(configuration.read) @width = @configuration[:width] @height = @configuration[:height] || -1 @slowdown = @configuration[:slowdown] || 1 @frames = Gosu::Image.load_tiles(window, base+'.png', @width, @height, false) @height = @frames.first.height if @height == -1 else #png, non animated @frames = [Gosu::Image.new(window, path)] @width = @frames.first.width @height = @frames.first.height @slowdown = 1 end @name = File.basename(path, File.extname(path)) # non-blurry image scaling #@frames.each {|f| f.retrofy } end def button_down(id) if id == Gosu::Button::KbEscape close end end - def draw frame, x,y,z + def draw frame, orientation, x,y,z #puts "#{@name} #{frame} #{@frames.length} = #{frame%@frames.length}" - @frames[(frame/@slowdown)%(@frames.length)].draw x,y,z + @frames[(frame/@slowdown)%(@frames.length)].draw x,y,z, orientation end def width @width end def height @height end end \ No newline at end of file
oneup/Puit
5920b274c6ac5b2e0379a4d82acb1d232d428fc7
move left
diff --git a/gameobjects/puit.rb b/gameobjects/puit.rb index bce0486..09cbbf4 100644 --- a/gameobjects/puit.rb +++ b/gameobjects/puit.rb @@ -1,28 +1,39 @@ class Puit < Gameobject def move_to x, y @x = x @y = y end def initialize super @sprite = @sprites[:walk_empty] end def update super @y += 2 if moving_right? @x += 2 + elsif moving_left? + @x -= 2 end end def move_right pressed @move_right = pressed end def moving_right? @move_right end + + def move_left pressed + @move_left = pressed + end + + def moving_left? + @move_left + end + end \ No newline at end of file
oneup/Puit
f129af25ccc8c096d6dc2c616f95f1436b2b7b11
quick'n'dirty collision detection using Rect from rubygame via chingu
diff --git a/Main.rb b/Main.rb index dbff593..8406f45 100644 --- a/Main.rb +++ b/Main.rb @@ -1,80 +1,94 @@ +# powered by Gosy Mac Bundle 0.7.15 + + # Do not include gosu.bundle into this template. # This is just here so you can run your game from the terminal, or # your favorite text editor, using `ruby Main.rb`. require "rubygems" rescue nil require 'gosu' +require "socket" require "lib/require_all" require_all "lib/**/*.rb" require_all "gameobjects/**/*.rb" def window $game end def game $game end class MyWindow < Gosu::Window attr_accessor :key_receivers def initialize super 640, 480, false $game = self self.caption = "Puit" @key_receivers = [] @player = Puit.new @player.keys = {Gosu::Button::KbRight => :move_right} @objects = [Background.new, @cursor = Mouse.new, @player] @keys = { Gosu::Button::KbEscape => :close } end def update @objects.each_send :update @cursor.move_to(mouse_x, mouse_y) if @cursor resolve_collisons end def draw @objects.each_send :draw end def button_down(id) @key_receivers.each do |object| object.button_down id end @keys.each do |button, method| if id == button self.send method end end end def button_up(id) @key_receivers.each do |object| object.button_up id end end def resolve_collisons + for i in ([email protected]) + o1 = @objects[i] + for k in (i+1)[email protected] + o2 = @objects[k] + if o1.collides_with o2 + o1.on_collision_with o2 if o1.respond_to? :on_collision_with + o2.on_collision_with o1 if o2.respond_to? :on_collision_with + end + end + end # end end MyWindow.new game.show diff --git a/gameobjects/background/background.rb b/gameobjects/background/background.rb index e4b7f38..836dc2f 100644 --- a/gameobjects/background/background.rb +++ b/gameobjects/background/background.rb @@ -1,4 +1,7 @@ class Background < Gameobject - def on_collision_with_puit + def on_collision_with object #_puit + if object.y > 400 + object.y = 400 + end end end \ No newline at end of file diff --git a/lib/geometry/Rect.rb b/lib/geometry/Rect.rb new file mode 100644 index 0000000..47b197a --- /dev/null +++ b/lib/geometry/Rect.rb @@ -0,0 +1,609 @@ +#-- +# Rubygame -- Ruby code and bindings to SDL to facilitate game creation +# Copyright (C) 2004-2007 John Croisant +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +#++ + +#-- +# Table of Contents: +# +# class Rect +# GENERAL: +# initialize +# new_from_object +# to_s +# to_a, to_ary +# [] +# ATTRIBUTES: +# x, y, w, h [<- accessors] +# width, height, size +# left, top, right, bottom +# center, centerx, centery +# topleft, topright +# bottomleft, bottomright +# midleft, midtop, midright, midbottom +# UTILITY METHODS: +# clamp, clamp! +# clip, clip! +# collide_hash, collide_hash_all +# collide_array, collide_array_all +# collide_point? +# collide_rect? +# contain? +# inflate, inflate! +# move, move! +# normalize, normalize! +# union, union! +# union_all, union_all! +# +# class Surface +# make_rect +# +#++ + + +# A Rect is a representation of a rectangle, with four core attributes +# (x offset, y offset, width, and height) and a variety of functions +# for manipulating and accessing these attributes. +# +# Like all coordinates in Rubygame (and its base library, SDL), x and y +# offsets are measured from the top-left corner of the screen, with greater +# y offsets being lower. Thus, specifying the x and y offsets of the Rect +# is equivalent to setting the location of its top-left corner. +# +# In Rubygame, Rects are used for collision detection and describing +# the area of a Surface to operate on. +class Rect < Array + + #-- + # GENERAL + #++ + + # Create a new Rect, attempting to extract its own information from + # the given arguments. The arguments must fall into one of these cases: + # + # - 4 integers +(x, y, w, h)+. + # - 1 Rect or Array containing 4 integers +([x, y, w, h])+. + # - 2 Arrays containing 2 integers each +([x,y], [w,h])+. + # - 1 object with a +rect+ attribute which is a valid Rect object. + # + # All rect core attributes (x,y,w,h) must be integers. + # + def initialize(*argv) + case argv.length + when 1 + if argv[0].kind_of? Array; super(argv[0]) + elsif argv[0].respond_to? :rect; super(argv[0]) + end + when 2 + super(argv[0].concat(argv[1])) + when 4 + super(argv) + end + return self + end + + # Extract or generate a Rect from the given object, if possible, using the + # following process: + # + # 1. If it's a Rect already, return a duplicate Rect. + # 2. Elsif it's an Array with at least 4 values, make a Rect from it. + # 3. Elsif it has a +rect+ attribute., perform (1) and (2) on that. + # 4. Otherwise, raise TypeError. + # + # See also Surface#make_rect() + def Rect.new_from_object(object) + case(object) + when Rect + return object.dup + when Array + if object.length >= 4 + return Rect.new(object) + else + raise(ArgumentError,"Array does not have enough indices to be made into a Rect (%d for 4)."%object.length ) + end + else + begin + case(object.rect) + when Rect + return object.rect.dup + when Array + if object.rect.length >= 4 + return Rect.new(object.rect) + else + raise(ArgumentError,"Array does not have enough indices to be made into a Rect (%d for 4)."%object.rect.length ) + end + end # case object.rect + rescue NoMethodError # if no rect.rect + raise(TypeError,"Object must be a Rect or Array [x,y,w,h], or have an attribute called 'rect'. (Got %s instance.)"%object.class) + end + end # case object + end + + + # Print the Rect in the form "+#<Rect [x,y,w,h]>+" + def to_s; "#<Rect [%s,%s,%s,%s]>"%self; end + + # Print the Rect in the form "+#<Rect:id [x,y,w,h]>+" + def inspect; "#<Rect:#{self.object_id} [%s,%s,%s,%s]>"%self; end + + #-- + # ATTRIBUTES + #++ + + # Returns self.at(0) + def x; return self.at(0); end + # Sets self[0] to +val+ + def x=(val); self[0] = val; end + + alias left x + alias left= x=; + alias l x + alias l= x=; + + # Returns self.at(1) + def y; return self.at(1); end + # Sets self[1] to +val+ + def y=(val); self[1] = val; end + + alias top y + alias top= y=; + alias t y + alias t= y=; + + # Returns self.at(2) + def w; return self.at(2); end + # Sets self[2] to +val+ + def w=(val); self[2] = val; end + + alias width w + alias width= w=; + + # Returns self.at(3) + def h; return self.at(3); end + # Sets self[3] to +val+ + def h=(val); self[3] = val; end + + alias height h + alias height= h=; + + # Return the width and height of the Rect. + def size; return self[2,2]; end + + # Set the width and height of the Rect. + def size=(size) + raise ArgumentError, "Rect#size= takes an Array of form [width, height]." if size.size != 2 + self[2,2] = size + size + end + + # Return the x coordinate of the right side of the Rect. + def right; return self.at(0)+self.at(2); end + + # Set the x coordinate of the right side of the Rect by translating the + # Rect (adjusting the x offset). + def right=(r); self[0] = r - self.at(2); return r; end + + alias r right + alias r= right=; + + # Return the y coordinate of the bottom side of the Rect. + def bottom; return self.at(1)+self.at(3); end + + # Set the y coordinate of the bottom side of the Rect by translating the + # Rect (adjusting the y offset). + def bottom=(b); self[1] = b - self.at(3); return b; end + + alias b bottom + alias b= bottom=; + + # Return the x and y coordinates of the center of the Rect. + def center; return self.centerx, self.centery; end + + # Set the x and y coordinates of the center of the Rect by translating the + # Rect (adjusting the x and y offsets). + def center=(center) + raise ArgumentError, "Rect#center= takes an Array of the form [x,y]." if center.size != 2 + self.centerx, self.centery = center + center + end + alias c center + alias c= center=; + + # Return the x coordinate of the center of the Rect + def centerx; return self.at(0)+(self.at(2).div(2)); end + + # Set the x coordinate of the center of the Rect by translating the + # Rect (adjusting the x offset). + def centerx=(x); self[0] = x - (self.at(2).div(2)); return x; end + + alias cx centerx + alias cx= centerx=; + + # Return the y coordinate of the center of the Rect + def centery; return self.at(1)+(self.at(3).div(2)); end + + # Set the y coordinate of the center of the Rect by translating the + # Rect (adjusting the y offset). + def centery=(y); self[1] = y- (self.at(3).div(2)); return y; end + + alias cy centery + alias cy= centery=; + + # Return the x and y coordinates of the top-left corner of the Rect + def topleft; return self[0,2].to_a; end + + # Set the x and y coordinates of the top-left corner of the Rect by + # translating the Rect (adjusting the x and y offsets). + def topleft=(topleft) + raise ArgumentError, "Rect#topright= takes an Array of form [x, y]." if topleft.size != 2 + self[0,2] = topleft + return topleft + end + + alias tl topleft + alias tl= topleft=; + + # Return the x and y coordinates of the top-right corner of the Rect + def topright; return self.right, self.at(1); end + + # Set the x and y coordinates of the top-right corner of the Rect by + # translating the Rect (adjusting the x and y offsets). + def topright=(topright) + raise ArgumentError, "Rect#topright= takes an Array of form [x, y]." if topright.size != 2 + self.right, self[1] = topright + return topright + end + + alias tr topright + alias tr= topright=; + + # Return the x and y coordinates of the bottom-left corner of the Rect + def bottomleft; return self.at(0), self.bottom; end + + # Set the x and y coordinates of the bottom-left corner of the Rect by + # translating the Rect (adjusting the x and y offsets). + def bottomleft=(bottomleft) + raise ArgumentError, "Rect#bottomleft= takes an Array of form [x, y]." if bottomleft.size != 2 + self[0], self.bottom = bottomleft + return bottomleft + end + + alias bl bottomleft + alias bl= bottomleft=; + + # Return the x and y coordinates of the bottom-right corner of the Rect + def bottomright; return self.right, self.bottom; end + + # Set the x and y coordinates of the bottom-right corner of the Rect by + # translating the Rect (adjusting the x and y offsets). + def bottomright=(bottomright) + raise ArgumentError, "Rect#bottomright= takes an Array of form [x, y]." if bottomright.size != 2 + self.right, self.bottom = bottomright + return bottomright + end + + alias br bottomright + alias br= bottomright=; + + # Return the x and y coordinates of the midpoint on the left side of the + # Rect. + def midleft; return self.at(0), self.centery; end + + # Set the x and y coordinates of the midpoint on the left side of the Rect + # by translating the Rect (adjusting the x and y offsets). + def midleft=(midleft) + raise ArgumentError, "Rect#midleft= takes an Array of form [x, y]." if midleft.size != 2 + self[0], self.centery = midleft + return midleft + end + + alias ml midleft + alias ml= midleft=; + + # Return the x and y coordinates of the midpoint on the left side of the + # Rect. + def midtop; return self.centerx, self.at(1); end + + # Set the x and y coordinates of the midpoint on the top side of the Rect + # by translating the Rect (adjusting the x and y offsets). + def midtop=(midtop) + raise ArgumentError, "Rect#midtop= takes an Array of form [x, y]." if midtop.size != 2 + self.centerx, self[1] = midtop + return midtop + end + + alias mt midtop + alias mt= midtop=; + + # Return the x and y coordinates of the midpoint on the left side of the + # Rect. + def midright; return self.right, self.centery; end + + # Set the x and y coordinates of the midpoint on the right side of the Rect + # by translating the Rect (adjusting the x and y offsets). + def midright=(midright) + raise ArgumentError, "Rect#midright= takes an Array of form [x, y]." if midright.size != 2 + self.right, self.centery = midright + return midright + end + + alias mr midright + alias mr= midright=; + + # Return the x and y coordinates of the midpoint on the left side of the + # Rect. + def midbottom; return self.centerx, self.bottom; end + + # Set the x and y coordinates of the midpoint on the bottom side of the + # Rect by translating the Rect (adjusting the x and y offsets). + def midbottom=(midbottom) + raise ArgumentError, "Rect#midbottom= takes an Array of form [x, y]." if midbottom.size != 2 + self.centerx, self.bottom = midbottom + return midbottom + end + + alias mb midbottom + alias mb= midbottom=; + + #-- + # UTILITY METHODS + #++ + + + # As #clamp!, but the original caller is not changed. + def clamp(rect) + self.dup.clamp!(rect) + end + + # Translate the calling Rect to be entirely inside the given Rect. If + # the caller is too large along either axis to fit in the given rect, + # it is centered with respect to the given rect, along that axis. + def clamp!(rect) + nself = self.normalize + rect = Rect.new_from_object(rect) + #If self is inside given, there is no need to move self + unless rect.contain?(nself) + + #If self is too wide: + if nself.at(2) >= rect.at(2) + self[0] = rect.centerx - nself.at(2).div(2) + #Else self is not too wide + else + #If self is to the left of arg + if nself.at(0) < rect.at(0) + self[0] = rect.at(0) + #If self is to the right of arg + elsif nself.right > rect.right + self[0] = rect.right - nself.at(2) + #Otherwise, leave x alone + end + end + + #If self is too tall: + if nself.at(3) >= rect.at(3) + self[1] = rect.centery - nself.at(3).div(2) + #Else self is not too tall + else + #If self is above arg + if nself.at(1) < rect.at(1) + self[1] = rect.at(1) + #If self below arg + elsif nself.bottom > rect.bottom + self[1] = rect.bottom - nself.at(3) + #Otherwise, leave y alone + end + end + end + return self + end + + # As #clip!, but the original caller is not changed. + def clip(rect) + self.dup.clip!(rect) + end + + # Crop the calling Rect to be entirely inside the given Rect. If the + # caller does not intersect the given Rect at all, its width and height + # are set to zero, but its x and y offsets are not changed. + # + # As a side effect, the Rect is normalized. + def clip!(rect) + nself = self.normalize + other = Rect.new_from_object(rect).normalize! + if self.collide_rect?(other) + self[0] = [nself.at(0), other.at(0)].max + self[1] = [nself.at(1), other.at(1)].max + self[2] = [nself.right, other.right].min - self.at(0) + self[3] = [nself.bottom, other.bottom].min - self.at(1) + else #if they do not intersect at all: + self[0], self[1] = nself.topleft + self[2], self[3] = 0, 0 + end + return self + end + + # Iterate through all key/value pairs in the given hash table, and + # return the first pair whose value is a Rect that collides with the + # caller. + # + # Because a hash table is unordered, you should not expect any + # particular Rect to be returned first. + def collide_hash(hash_rects) + hash_rects.each { |key,value| + if value.collide_rect?+(self); return [key,value]; end + } + return nil + end + + # Iterate through all key/value pairs in the given hash table, and + # return an Array of every pair whose value is a Rect that collides + # the caller. + # + # Because a hash table is unordered, you should not expect the returned + # pairs to be in any particular order. + def collide_hash_all(hash_rects) + hash_rects.select { |key,value| + value.collide_rect?+(self) + } + end + + # Iterate through all elements in the given Array, and return + # the *index* of the first element which is a Rect that collides with + # the caller. + def collide_array(array_rects) + for i in (0...(array_rects.length)) + if array_rects[i].collide_rect?(self) + return i + end + end + return nil + end + + # Iterate through all elements in the given Array, and return + # an Array containing the *indices* of every element that is a Rect + # that collides with the caller. + def collide_array_all(array_rects) + indexes = [] + for i in (0...(array_rects.length)) + if array_rects[i].collide_rect?(self) + indexes += [i] + end + end + return indexes + end + + # True if the point is inside (including on the border) of the caller. + # If you have Array of coordinates, you can use collide_point?(*coords). + def collide_point?(x,y) + nself = normalize() + x.between?(nself.left,nself.right) && y.between?(nself.top,nself.bottom) + end + + # True if the caller and the given Rect overlap (or touch) at all. + def collide_rect?(rect) + nself = self.normalize + rect = Rect.new_from_object(rect).normalize! + return ((nself.l >= rect.l && nself.l <= rect.r) or (rect.l >= nself.l && rect.l <= nself.r)) && + ((nself.t >= rect.t && nself.t <= rect.b) or (rect.t >= nself.t && rect.t <= nself.b)) + end + + # True if the given Rect is totally within the caller. Borders may + # overlap. + def contain?(rect) + nself = self.normalize + rect = Rect.new_from_object(rect).normalize! + return (nself.left <= rect.left and rect.right <= nself.right and + nself.top <= rect.top and rect.bottom <= nself.bottom) + end + + # As #inflate!, but the original caller is not changed. + def inflate(x,y) + return self.class.new(self.at(0) - x.div(2), + self.at(1) - y.div(2), + self.at(2) + x, + self.at(3) + y) + end + + # Increase the Rect's size is the x and y directions, while keeping the + # same center point. For best results, expand by an even number. + # X and y inflation can be given as an Array or as separate values. + def inflate!(x,y) + self[0] -= x.div(2) + self[1] -= y.div(2) + self[2] += x + self[3] += y + return self + end + + # As #move!, but the original caller is not changed. + def move(x,y) + self.dup.move!(x,y) + end + + # Translate the Rect by the given amounts in the x and y directions. + # Positive values are rightward for x and downward for y. + # X and y movement can be given as an Array or as separate values. + def move!(x,y) + self[0]+=x; self[1]+=y + return self + end + + # As #normalize!, but the original caller is not changed. + def normalize + self.dup.normalize!() + end + + # Fix Rects that have negative width or height, without changing the + # area it represents. Has no effect on Rects with non-negative width + # and height. Some Rect methods will automatically normalize the Rect. + def normalize! + if self.at(2) < 0 + self[0], self[2] = self.at(0)+self.at(2), -self.at(2) + end + if self.at(3) < 0 + self[1], self[3] = self.at(1)+self.at(3), -self.at(3) + end + self + end + + # As #union!, but the original caller is not changed. + def union(rect) + self.dup.union!(rect) + end + + # Expand the caller to also cover the given Rect. The Rect is still a + # rectangle, so it may also cover areas that neither of the original + # Rects did, for example areas between the two Rects. + def union!(rect) + self.normalize! + rleft, rtop = self.topleft + rright, rbottom = self.bottomright + r2 = Rect.new_from_object(rect).normalize! + + rleft = [rleft, r2.left].min + rtop = [rtop, r2.top].min + rright = [rright, r2.right].max + rbottom = [rbottom, r2.bottom].max + + self[0,4] = rleft, rtop, rright - rleft, rbottom - rtop + return self + end + + # As #union_all!, but the original caller is not changed. + def union_all(array_rects) + self.dup.union_all!(array_rects) + end + + # Expand the caller to cover all of the given Rects. See also #union! + def union_all!(array_rects) + array_rects.each do |r| + self.union!(r) + end + return self + end + + +end # class Rect + + +class Surface + # Return a Rect with the same width and height as the Surface, positioned + # at (0,0). + def make_rect() + return Rect.new(0,0,self.width,self.height) + end +end diff --git a/lib/spriter/gameobject.rb b/lib/spriter/gameobject.rb index 8f503aa..e84bf46 100644 --- a/lib/spriter/gameobject.rb +++ b/lib/spriter/gameobject.rb @@ -1,62 +1,74 @@ class Gameobject + attr_accessor :bounds, :x, :y, :width, :height + def initialize # object containment @parent = game # animations @sprites = {} # simple file simple_file = "gameobjects/#{self.class.name.downcase}.png" if FileTest.exist? simple_file @sprite = simple_file.png @sprites[:default] = @sprite else #directory contents Dir.glob("gameobjects/#{self.class.name.downcase}/*.png").collect do |e| #animation_config_yml = File.join(File.dirname(path), File.basename(path, ".yml")) # make sprite class - sprite can be unanimated or animated image. # the missing class from gosu (adding game layer) #[ ] the gosu bundle does not support yml - make own format sprite_symbol = File.basename(e, File.extname(e)).to_sym sprite = Sprite.new e @sprites[sprite_symbol] = sprite @sprite = @sprites[sprite_symbol] end #puts @sprites end @age = 0 @x = @y = 0 @z = 0 # dir.glob classname + @bounds = Rect.new(@x, @y, @sprite.width, @sprite.height) + if self.respond_to? :setup self.setup end end + def sprite= what + @sprite = @sprites[what] + end + def update @age += 1 end def draw @sprite.draw(@age, @x,@y,@z) end def keys= keybindings @keys = keybindings game.key_receivers << self end def button_down id if @keys[id] self.send @keys[id], true end end def button_up id if @keys[id] self.send @keys[id], false end end + + def collides_with object + self.bounds.collide_rect? object.bounds + end end \ No newline at end of file diff --git a/lib/spriter/sprite.rb b/lib/spriter/sprite.rb index 2e76ec9..a738fba 100644 --- a/lib/spriter/sprite.rb +++ b/lib/spriter/sprite.rb @@ -1,41 +1,51 @@ # Sprites can either be # .png = non-animated # .png + .irb = animated # class Sprite def initialize(path) base = File.join(File.dirname(path), File.basename(path, File.extname(path))) configuration = base+".irb" if configuration.exists? @configuration = eval(configuration.read) @width = @configuration[:width] @height = @configuration[:height] || -1 @slowdown = @configuration[:slowdown] || 1 @frames = Gosu::Image.load_tiles(window, base+'.png', @width, @height, false) + + @height = @frames.first.height if @height == -1 else #png, non animated @frames = [Gosu::Image.new(window, path)] @width = @frames.first.width @height = @frames.first.height @slowdown = 1 end @name = File.basename(path, File.extname(path)) # non-blurry image scaling #@frames.each {|f| f.retrofy } end def button_down(id) if id == Gosu::Button::KbEscape close end end def draw frame, x,y,z #puts "#{@name} #{frame} #{@frames.length} = #{frame%@frames.length}" @frames[(frame/@slowdown)%(@frames.length)].draw x,y,z end + + def width + @width + end + + def height + @height + end end \ No newline at end of file
oneup/Puit
89a26ea415b42c5c9aae2e47573c1c07d8615ebd
basic key dispatcher
diff --git a/Main.rb b/Main.rb index 0ae7ef4..dbff593 100644 --- a/Main.rb +++ b/Main.rb @@ -1,65 +1,80 @@ # Do not include gosu.bundle into this template. # This is just here so you can run your game from the terminal, or # your favorite text editor, using `ruby Main.rb`. require "rubygems" rescue nil require 'gosu' require "lib/require_all" require_all "lib/**/*.rb" require_all "gameobjects/**/*.rb" def window $game end def game $game end class MyWindow < Gosu::Window + attr_accessor :key_receivers + def initialize super 640, 480, false $game = self - self.caption = "Puit" + self.caption = "Puit" + + @key_receivers = [] + @player = Puit.new @player.keys = {Gosu::Button::KbRight => :move_right} @objects = [Background.new, @cursor = Mouse.new, @player] + @keys = { Gosu::Button::KbEscape => :close } end def update @objects.each_send :update @cursor.move_to(mouse_x, mouse_y) if @cursor resolve_collisons end def draw @objects.each_send :draw end def button_down(id) - + @key_receivers.each do |object| + object.button_down id + end + @keys.each do |button, method| if id == button self.send method end end end + def button_up(id) + @key_receivers.each do |object| + object.button_up id + end + end + def resolve_collisons # end end MyWindow.new game.show diff --git a/gameobjects/puit.rb b/gameobjects/puit.rb index e34cd7d..bce0486 100644 --- a/gameobjects/puit.rb +++ b/gameobjects/puit.rb @@ -1,24 +1,28 @@ class Puit < Gameobject def move_to x, y @x = x @y = y end def initialize super @sprite = @sprites[:walk_empty] end def update super @y += 2 + + if moving_right? + @x += 2 + end end - def move_right - @x += 2 + def move_right pressed + @move_right = pressed end - - def keys= keybindings - # todo + + def moving_right? + @move_right end end \ No newline at end of file diff --git a/lib/spriter/gameobject.rb b/lib/spriter/gameobject.rb index d7db9ae..8f503aa 100644 --- a/lib/spriter/gameobject.rb +++ b/lib/spriter/gameobject.rb @@ -1,45 +1,62 @@ class Gameobject def initialize # object containment @parent = game # animations @sprites = {} # simple file simple_file = "gameobjects/#{self.class.name.downcase}.png" if FileTest.exist? simple_file @sprite = simple_file.png @sprites[:default] = @sprite else #directory contents Dir.glob("gameobjects/#{self.class.name.downcase}/*.png").collect do |e| #animation_config_yml = File.join(File.dirname(path), File.basename(path, ".yml")) # make sprite class - sprite can be unanimated or animated image. # the missing class from gosu (adding game layer) #[ ] the gosu bundle does not support yml - make own format sprite_symbol = File.basename(e, File.extname(e)).to_sym sprite = Sprite.new e @sprites[sprite_symbol] = sprite @sprite = @sprites[sprite_symbol] end #puts @sprites end @age = 0 @x = @y = 0 @z = 0 # dir.glob classname if self.respond_to? :setup self.setup end end def update @age += 1 end def draw @sprite.draw(@age, @x,@y,@z) end + + def keys= keybindings + @keys = keybindings + game.key_receivers << self + end + + def button_down id + if @keys[id] + self.send @keys[id], true + end + end + + def button_up id + if @keys[id] + self.send @keys[id], false + end + end end \ No newline at end of file
oneup/Puit
0a354cceb675ce3d39b45a1b4be944a0ab03b5b9
walk animation, sprite class extended
diff --git a/Main.rb b/Main.rb index 1fc122e..0ae7ef4 100644 --- a/Main.rb +++ b/Main.rb @@ -1,47 +1,65 @@ # Do not include gosu.bundle into this template. # This is just here so you can run your game from the terminal, or # your favorite text editor, using `ruby Main.rb`. require "rubygems" rescue nil require 'gosu' require "lib/require_all" require_all "lib/**/*.rb" require_all "gameobjects/**/*.rb" def window $game end def game $game end + class MyWindow < Gosu::Window def initialize super 640, 480, false $game = self self.caption = "Puit" - @objects = [Background.new, @cursor = Mouse.new, Puit.new] - @sprite = Sprite.new "gameobjects/puit/walk_empty.png" + @player = Puit.new + @player.keys = {Gosu::Button::KbRight => :move_right} + + @objects = [Background.new, @cursor = Mouse.new, @player] + + @keys = { Gosu::Button::KbEscape => :close } end def update @objects.each_send :update - - if "gameobjects/puit/stand_empty.png".exists? - @cursor.move_to(mouse_x, mouse_y) if @cursor - end + + @cursor.move_to(mouse_x, mouse_y) if @cursor + + resolve_collisons end def draw @objects.each_send :draw end + + def button_down(id) + + @keys.each do |button, method| + if id == button + self.send method + end + end + end + + def resolve_collisons + # + end end MyWindow.new -game.show \ No newline at end of file +game.show diff --git a/gameobjects/background/background.rb b/gameobjects/background/background.rb index cd85d85..e4b7f38 100644 --- a/gameobjects/background/background.rb +++ b/gameobjects/background/background.rb @@ -1,2 +1,4 @@ class Background < Gameobject + def on_collision_with_puit + end end \ No newline at end of file diff --git a/gameobjects/puit.rb b/gameobjects/puit.rb index dd3f528..e34cd7d 100644 --- a/gameobjects/puit.rb +++ b/gameobjects/puit.rb @@ -1,11 +1,24 @@ class Puit < Gameobject def move_to x, y @x = x @y = y end def initialize super @sprite = @sprites[:walk_empty] end + + def update + super + @y += 2 + end + + def move_right + @x += 2 + end + + def keys= keybindings + # todo + end end \ No newline at end of file diff --git a/gameobjects/puit/walk_empty.irb b/gameobjects/puit/walk_empty.irb index ef62c6f..0e6b8d0 100644 --- a/gameobjects/puit/walk_empty.irb +++ b/gameobjects/puit/walk_empty.irb @@ -1 +1 @@ -{:width => 16, :slowdown => 3} \ No newline at end of file +{:width => 15, :slowdown => 8} \ No newline at end of file diff --git a/gameobjects/puit/walk_empty.png b/gameobjects/puit/walk_empty.png index f7d1f45..ff10069 100644 Binary files a/gameobjects/puit/walk_empty.png and b/gameobjects/puit/walk_empty.png differ diff --git a/lib/spriter/gameobject.rb b/lib/spriter/gameobject.rb index 547ba50..d7db9ae 100644 --- a/lib/spriter/gameobject.rb +++ b/lib/spriter/gameobject.rb @@ -1,40 +1,45 @@ class Gameobject def initialize + # object containment + @parent = game + + # animations @sprites = {} # simple file simple_file = "gameobjects/#{self.class.name.downcase}.png" if FileTest.exist? simple_file @sprite = simple_file.png @sprites[:default] = @sprite else #directory contents Dir.glob("gameobjects/#{self.class.name.downcase}/*.png").collect do |e| #animation_config_yml = File.join(File.dirname(path), File.basename(path, ".yml")) # make sprite class - sprite can be unanimated or animated image. # the missing class from gosu (adding game layer) #[ ] the gosu bundle does not support yml - make own format sprite_symbol = File.basename(e, File.extname(e)).to_sym sprite = Sprite.new e @sprites[sprite_symbol] = sprite @sprite = @sprites[sprite_symbol] end - #puts @sprites end - + + @age = 0 @x = @y = 0 @z = 0 # dir.glob classname if self.respond_to? :setup self.setup end end def update + @age += 1 end def draw - @sprite.draw(@x,@y,@z) + @sprite.draw(@age, @x,@y,@z) end end \ No newline at end of file diff --git a/lib/spriter/sprite.rb b/lib/spriter/sprite.rb index 9237285..2e76ec9 100644 --- a/lib/spriter/sprite.rb +++ b/lib/spriter/sprite.rb @@ -1,25 +1,41 @@ # Sprites can either be # .png = non-animated # .png + .irb = animated # class Sprite def initialize(path) base = File.join(File.dirname(path), File.basename(path, File.extname(path))) configuration = base+".irb" if configuration.exists? @configuration = eval(configuration.read) @width = @configuration[:width] @height = @configuration[:height] || -1 + @slowdown = @configuration[:slowdown] || 1 @frames = Gosu::Image.load_tiles(window, base+'.png', @width, @height, false) else #png, non animated @frames = [Gosu::Image.new(window, path)] + + @width = @frames.first.width + @height = @frames.first.height + @slowdown = 1 + end + @name = File.basename(path, File.extname(path)) + + # non-blurry image scaling + #@frames.each {|f| f.retrofy } + end + + def button_down(id) + if id == Gosu::Button::KbEscape + close end end - def draw x,y,z - @frames[0].draw x,y,z + def draw frame, x,y,z + #puts "#{@name} #{frame} #{@frames.length} = #{frame%@frames.length}" + @frames[(frame/@slowdown)%(@frames.length)].draw x,y,z end end \ No newline at end of file
oneup/Puit
59403c72deaa3a83c825b47713450aa066a30de4
sprite switching
diff --git a/gameobjects/puit.rb b/gameobjects/puit.rb index 4eb4ae4..dd3f528 100644 --- a/gameobjects/puit.rb +++ b/gameobjects/puit.rb @@ -1,6 +1,11 @@ class Puit < Gameobject def move_to x, y @x = x @y = y end + + def initialize + super + @sprite = @sprites[:walk_empty] + end end \ No newline at end of file diff --git a/lib/spriter/gameobject.rb b/lib/spriter/gameobject.rb index b120109..547ba50 100644 --- a/lib/spriter/gameobject.rb +++ b/lib/spriter/gameobject.rb @@ -1,38 +1,40 @@ class Gameobject def initialize @sprites = {} # simple file simple_file = "gameobjects/#{self.class.name.downcase}.png" if FileTest.exist? simple_file @sprite = simple_file.png @sprites[:default] = @sprite else #directory contents Dir.glob("gameobjects/#{self.class.name.downcase}/*.png").collect do |e| #animation_config_yml = File.join(File.dirname(path), File.basename(path, ".yml")) # make sprite class - sprite can be unanimated or animated image. # the missing class from gosu (adding game layer) #[ ] the gosu bundle does not support yml - make own format - @sprites[File.basename(e, File.extname(e)).to_sym] = e.png - @sprite = e.png + sprite_symbol = File.basename(e, File.extname(e)).to_sym + sprite = Sprite.new e + @sprites[sprite_symbol] = sprite + @sprite = @sprites[sprite_symbol] end #puts @sprites end @x = @y = 0 @z = 0 # dir.glob classname if self.respond_to? :setup self.setup end end def update end def draw @sprite.draw(@x,@y,@z) end end \ No newline at end of file diff --git a/lib/spriter/sprite.rb b/lib/spriter/sprite.rb index 270943f..9237285 100644 --- a/lib/spriter/sprite.rb +++ b/lib/spriter/sprite.rb @@ -1,21 +1,25 @@ # Sprites can either be # .png = non-animated # .png + .irb = animated # class Sprite def initialize(path) base = File.join(File.dirname(path), File.basename(path, File.extname(path))) configuration = base+".irb" if configuration.exists? @configuration = eval(configuration.read) @width = @configuration[:width] @height = @configuration[:height] || -1 @frames = Gosu::Image.load_tiles(window, base+'.png', @width, @height, false) else #png, non animated @frames = [Gosu::Image.new(window, path)] end end + + def draw x,y,z + @frames[0].draw x,y,z + end end \ No newline at end of file
oneup/Puit
ff68e859f750c114880d54d6081e8c3d4e2c3176
background gameobject added
diff --git a/Main.rb b/Main.rb index 55584ce..1fc122e 100644 --- a/Main.rb +++ b/Main.rb @@ -1,38 +1,47 @@ # Do not include gosu.bundle into this template. # This is just here so you can run your game from the terminal, or # your favorite text editor, using `ruby Main.rb`. require "rubygems" rescue nil require 'gosu' require "lib/require_all" require_all "lib/**/*.rb" require_all "gameobjects/**/*.rb" + +def window + $game +end + def game $game end class MyWindow < Gosu::Window def initialize super 640, 480, false $game = self self.caption = "Puit" - @objects = [@cursor = Mouse.new, Puit.new] + @objects = [Background.new, @cursor = Mouse.new, Puit.new] + + @sprite = Sprite.new "gameobjects/puit/walk_empty.png" end def update @objects.each_send :update - @cursor.move_to(mouse_x, mouse_y) if @cursor + if "gameobjects/puit/stand_empty.png".exists? + @cursor.move_to(mouse_x, mouse_y) if @cursor + end end def draw @objects.each_send :draw end end MyWindow.new game.show \ No newline at end of file diff --git a/gameobjects/background/background.png b/gameobjects/background/background.png new file mode 100644 index 0000000..8d84e6d Binary files /dev/null and b/gameobjects/background/background.png differ diff --git a/gameobjects/background/background.rb b/gameobjects/background/background.rb new file mode 100644 index 0000000..cd85d85 --- /dev/null +++ b/gameobjects/background/background.rb @@ -0,0 +1,2 @@ +class Background < Gameobject +end \ No newline at end of file diff --git a/gameobjects/puit/walk_empty.irb b/gameobjects/puit/walk_empty.irb new file mode 100644 index 0000000..ef62c6f --- /dev/null +++ b/gameobjects/puit/walk_empty.irb @@ -0,0 +1 @@ +{:width => 16, :slowdown => 3} \ No newline at end of file diff --git a/gameobjects/puit/walk_empty.png b/gameobjects/puit/walk_empty.png new file mode 100644 index 0000000..f7d1f45 Binary files /dev/null and b/gameobjects/puit/walk_empty.png differ diff --git a/gameobjects/puit/walk_empty.yml b/gameobjects/puit/walk_empty.yml new file mode 100755 index 0000000..ba95788 --- /dev/null +++ b/gameobjects/puit/walk_empty.yml @@ -0,0 +1,2 @@ +width: 16 # pixel width of a single frame +slowdown: 3 \ No newline at end of file
oneup/Puit
f1afd414c1025e5766345299b908d5d56bf61117
basic sprite autoloading
diff --git a/gameobjects/puit/mouse.png b/gameobjects/puit/mouse.png deleted file mode 100644 index f5e1a06..0000000 Binary files a/gameobjects/puit/mouse.png and /dev/null differ diff --git a/lib/helpers.rb b/lib/helpers.rb index cef3d0e..0b53f48 100644 --- a/lib/helpers.rb +++ b/lib/helpers.rb @@ -1,82 +1,90 @@ class Array def each_send what self.each do |e| e.send what end end end class Object def to_yml(f) File.open(f, "w") do |e| e.write self.to_yaml end self # return self so we can continue using that end end def load_image(name) Gosu::Image.new(game, name) end def scatter(measure) # @to named_fractions randomly_between(-measure..measure) end class String def png file_name = self $images ||= {} $images[file_name] ||= Gosu::Image.new(game, file_name) end - def yml $yaml ||= {} $yaml[self] ||= YAML.load_file(self) rescue nil end def from_yml yml end def draw(x,y,z) file_name = self $images ||= {} # level 1 ca$h $images[file_name] ||= load_image(file_name) # level 2 ca$h ca$hed loaRDing end def font(size=20) cache_name = self + size.to_s font_name = self $fonts ||= {} $fonts[cache_name] ||= Gosu::Font.new(game, font_name, size) end def play() cache_name = self $songs ||= {} $songs[cache_name] ||= Gosu::Sample.new($game, cache_name) $songs[cache_name].play end def require # full directory wide require Dir.glob(self).sort.reverse.each do |e| require e end end + + def exists? + FileTest.exist? self + end + def read + File.open(self) do |f| + return f.read + end + end def method_missing(method, *args) # and resend that method to that object # INSTANT PWNZORING # when unknown method, assume it an image or sound # turns all strings into sound/image file system objects $cache ||= {} $cache[self] = Gosu::Image.new($game, self) rescue Gosu::Sample.new($game, self) $cache[self].send method, args # "resources/sprites/bla.png".draw(0,0) end end diff --git a/lib/spriter/gameobject.rb b/lib/spriter/gameobject.rb index acef217..b120109 100644 --- a/lib/spriter/gameobject.rb +++ b/lib/spriter/gameobject.rb @@ -1,30 +1,38 @@ class Gameobject def initialize @sprites = {} # simple file simple_file = "gameobjects/#{self.class.name.downcase}.png" if FileTest.exist? simple_file @sprite = simple_file.png @sprites[:default] = @sprite else #directory contents Dir.glob("gameobjects/#{self.class.name.downcase}/*.png").collect do |e| - @sprites[File.basename(e).gsub(".png", "").to_sym] = e.png + #animation_config_yml = File.join(File.dirname(path), File.basename(path, ".yml")) + # make sprite class - sprite can be unanimated or animated image. + # the missing class from gosu (adding game layer) + #[ ] the gosu bundle does not support yml - make own format + @sprites[File.basename(e, File.extname(e)).to_sym] = e.png @sprite = e.png end #puts @sprites end @x = @y = 0 @z = 0 # dir.glob classname + + if self.respond_to? :setup + self.setup + end end def update end def draw @sprite.draw(@x,@y,@z) end end \ No newline at end of file diff --git a/lib/spriter/sprite.rb b/lib/spriter/sprite.rb new file mode 100644 index 0000000..270943f --- /dev/null +++ b/lib/spriter/sprite.rb @@ -0,0 +1,21 @@ + +# Sprites can either be +# .png = non-animated +# .png + .irb = animated +# +class Sprite + def initialize(path) + base = File.join(File.dirname(path), File.basename(path, File.extname(path))) + configuration = base+".irb" + + if configuration.exists? + @configuration = eval(configuration.read) + @width = @configuration[:width] + @height = @configuration[:height] || -1 + + @frames = Gosu::Image.load_tiles(window, base+'.png', @width, @height, false) + else #png, non animated + @frames = [Gosu::Image.new(window, path)] + end + end +end \ No newline at end of file
oneup/Puit
3b73ca9befd7d326f0478a067fbcc67a9cdfbee2
autoloading for resources
diff --git a/Main.rb b/Main.rb index feded3c..55584ce 100644 --- a/Main.rb +++ b/Main.rb @@ -1,39 +1,38 @@ # Do not include gosu.bundle into this template. # This is just here so you can run your game from the terminal, or # your favorite text editor, using `ruby Main.rb`. require "rubygems" rescue nil require 'gosu' require "lib/require_all" require_all "lib/**/*.rb" require_all "gameobjects/**/*.rb" def game $game end class MyWindow < Gosu::Window def initialize super 640, 480, false $game = self self.caption = "Puit" - @objects = [@cursor = Mouse.new] + @objects = [@cursor = Mouse.new, Puit.new] end def update @objects.each_send :update @cursor.move_to(mouse_x, mouse_y) if @cursor end def draw @objects.each_send :draw end end -MyWindow.new - +MyWindow.new game.show \ No newline at end of file diff --git a/TODO b/TODO index de1394e..74e0205 100644 --- a/TODO +++ b/TODO @@ -1,4 +1,5 @@ migrate cutewars/kyoto step by step. also integrate ideas from chingu -.... 1 [ ] bring poit+cursorkey back \ No newline at end of file +[ ] static sprites +[ ] moving poit sprites \ No newline at end of file diff --git a/gameobjects/puit.rb b/gameobjects/puit.rb new file mode 100644 index 0000000..4eb4ae4 --- /dev/null +++ b/gameobjects/puit.rb @@ -0,0 +1,6 @@ +class Puit < Gameobject + def move_to x, y + @x = x + @y = y + end +end \ No newline at end of file diff --git a/gameobjects/puit/mouse.png b/gameobjects/puit/mouse.png new file mode 100644 index 0000000..f5e1a06 Binary files /dev/null and b/gameobjects/puit/mouse.png differ diff --git a/gameobjects/puit/stand_empty.png b/gameobjects/puit/stand_empty.png new file mode 100755 index 0000000..af774fd Binary files /dev/null and b/gameobjects/puit/stand_empty.png differ diff --git a/lib/spriter/gameobject.rb b/lib/spriter/gameobject.rb index 8afaaf1..acef217 100644 --- a/lib/spriter/gameobject.rb +++ b/lib/spriter/gameobject.rb @@ -1,15 +1,30 @@ class Gameobject def initialize - @sprite = "gameobjects/#{self.class.name.downcase}.png".png + @sprites = {} + # simple file + simple_file = "gameobjects/#{self.class.name.downcase}.png" + if FileTest.exist? simple_file + @sprite = simple_file.png + @sprites[:default] = @sprite + else + #directory contents + Dir.glob("gameobjects/#{self.class.name.downcase}/*.png").collect do |e| + @sprites[File.basename(e).gsub(".png", "").to_sym] = e.png + @sprite = e.png + end + + #puts @sprites + end + @x = @y = 0 @z = 0 # dir.glob classname end def update end def draw @sprite.draw(@x,@y,@z) end end \ No newline at end of file
oneup/Puit
322b2764a12bb841b4f1706ff5aa216b7f4f72b9
require_all is handy
diff --git a/Main.rb b/Main.rb index 66f0ce7..feded3c 100644 --- a/Main.rb +++ b/Main.rb @@ -1,39 +1,39 @@ # Do not include gosu.bundle into this template. # This is just here so you can run your game from the terminal, or # your favorite text editor, using `ruby Main.rb`. require "rubygems" rescue nil require 'gosu' -require "lib/helpers" -require "lib/spriter/gameobject" -require "gameobjects/mouse" +require "lib/require_all" +require_all "lib/**/*.rb" +require_all "gameobjects/**/*.rb" def game $game end class MyWindow < Gosu::Window def initialize super 640, 480, false $game = self self.caption = "Puit" @objects = [@cursor = Mouse.new] end def update @objects.each_send :update @cursor.move_to(mouse_x, mouse_y) if @cursor end def draw @objects.each_send :draw end end MyWindow.new game.show \ No newline at end of file diff --git a/TODO b/TODO new file mode 100644 index 0000000..de1394e --- /dev/null +++ b/TODO @@ -0,0 +1,4 @@ +migrate cutewars/kyoto step by step. +also integrate ideas from chingu + +.... 1 [ ] bring poit+cursorkey back \ No newline at end of file diff --git a/lib/require_all.rb b/lib/require_all.rb new file mode 100644 index 0000000..6f93ff8 --- /dev/null +++ b/lib/require_all.rb @@ -0,0 +1,134 @@ +#-- +# Copyright (C)2009 Tony Arcieri +# You can redistribute this under the terms of the MIT license +# See file LICENSE for details +#++ + +module RequireAll + # A wonderfully simple way to load your code. + # + # The easiest way to use require_all is to just point it at a directory + # containing a bunch of .rb files. These files can be nested under + # subdirectories as well: + # + # require_all 'lib' + # + # This will find all the .rb files under the lib directory and load them. + # The proper order to load them in will be determined automatically. + # + # If the dependencies between the matched files are unresolvable, it will + # throw the first unresolvable NameError. + # + # You can also give it a glob, which will enumerate all the matching files: + # + # require_all 'lib/**/*.rb' + # + # It will also accept an array of files: + # + # require_all Dir.glob("blah/**/*.rb").reject { |f| stupid_file(f) } + # + # Or if you want, just list the files directly as arguments: + # + # require_all 'lib/a.rb', 'lib/b.rb', 'lib/c.rb', 'lib/d.rb' + # + def require_all(*args) + # Handle passing an array as an argument + args.flatten! + + if args.size > 1 + # If we got a list, those be are files! + files = args + else + arg = args.first + begin + # Try assuming we're doing plain ol' require compat + stat = File.stat(arg) + + if stat.file? + files = [arg] + elsif stat.directory? + files = Dir.glob File.join(arg, '**', '*.rb') + else + raise ArgumentError, "#{arg} isn't a file or directory" + end + rescue Errno::ENOENT + # If the stat failed, maybe we have a glob! + files = Dir.glob arg + + # Maybe it's an .rb file and the .rb was omitted + if File.file?(arg + '.rb') + require(arg + '.rb') + return true + end + + # If we ain't got no files, the glob failed + raise LoadError, "no such file to load -- #{arg}" if files.empty? + end + end + + # If there's nothing to load, you're doing it wrong! + raise LoadError, "no files to load" if files.empty? + + files.map! { |file| File.expand_path file } + files.sort! + + begin + failed = [] + first_name_error = nil + + # Attempt to load each file, rescuing which ones raise NameError for + # undefined constants. Keep trying to successively reload files that + # previously caused NameErrors until they've all been loaded or no new + # files can be loaded, indicating unresolvable dependencies. + files.each do |file| + begin + require file + rescue NameError => ex + failed << file + first_name_error ||= ex + rescue ArgumentError => ex + # Work around ActiveSuport freaking out... *sigh* + # + # ActiveSupport sometimes throws these exceptions and I really + # have no idea why. Code loading will work successfully if these + # exceptions are swallowed, although I've run into strange + # nondeterministic behaviors with constants mysteriously vanishing. + # I've gone spelunking through dependencies.rb looking for what + # exactly is going on, but all I ended up doing was making my eyes + # bleed. + # + # FIXME: If you can understand ActiveSupport's dependencies.rb + # better than I do I would *love* to find a better solution + raise unless ex.message["is not missing constant"] + + STDERR.puts "Warning: require_all swallowed ActiveSupport 'is not missing constant' error" + STDERR.puts ex.backtrace[0..9] + end + end + + # If this pass didn't resolve any NameErrors, we've hit an unresolvable + # dependency, so raise one of the exceptions we encountered. + if failed.size == files.size + raise first_name_error + else + files = failed + end + end until failed.empty? + + true + end + + # Works like require_all, but paths are relative to the caller rather than + # the current working directory + def require_rel(*paths) + # Handle passing an array as an argument + paths.flatten! + + source_directory = File.dirname caller.first.sub(/:\d+$/, '') + paths.each do |path| + require_all File.join(source_directory, path) + end + end +end + +include RequireAll \ No newline at end of file
oneup/Puit
84f6fb13eae16490e2e029533c4d7b5a5cf8218d
cursor object follows mouse
diff --git a/Main.rb b/Main.rb index ee1592a..66f0ce7 100644 --- a/Main.rb +++ b/Main.rb @@ -1,37 +1,39 @@ # Do not include gosu.bundle into this template. # This is just here so you can run your game from the terminal, or # your favorite text editor, using `ruby Main.rb`. require "rubygems" rescue nil require 'gosu' require "lib/helpers" require "lib/spriter/gameobject" require "gameobjects/mouse" def game $game end class MyWindow < Gosu::Window def initialize super 640, 480, false $game = self self.caption = "Puit" - @objects = [Mouse.new] + @objects = [@cursor = Mouse.new] end def update @objects.each_send :update + + @cursor.move_to(mouse_x, mouse_y) if @cursor end def draw @objects.each_send :draw end end MyWindow.new game.show \ No newline at end of file diff --git a/gameobjects/mouse.rb b/gameobjects/mouse.rb index 793e981..8e03776 100644 --- a/gameobjects/mouse.rb +++ b/gameobjects/mouse.rb @@ -1,2 +1,6 @@ class Mouse < Gameobject + def move_to x, y + @x = x + @y = y + end end \ No newline at end of file diff --git a/lib/spriter/gameobject.rb b/lib/spriter/gameobject.rb index 58987b0..8afaaf1 100644 --- a/lib/spriter/gameobject.rb +++ b/lib/spriter/gameobject.rb @@ -1,13 +1,15 @@ class Gameobject def initialize @sprite = "gameobjects/#{self.class.name.downcase}.png".png + @x = @y = 0 + @z = 0 # dir.glob classname end def update end def draw - @sprite.draw(0,0,0) + @sprite.draw(@x,@y,@z) end end \ No newline at end of file
oneup/Puit
3c65e585ab175628ad6378c7ca9ec3e73ebe3f1b
mouse pointer, framework stuff
diff --git a/Main.rb b/Main.rb index 8d802a2..ee1592a 100644 --- a/Main.rb +++ b/Main.rb @@ -1,22 +1,37 @@ # Do not include gosu.bundle into this template. # This is just here so you can run your game from the terminal, or # your favorite text editor, using `ruby Main.rb`. require "rubygems" rescue nil require 'gosu' + require "lib/helpers" +require "lib/spriter/gameobject" +require "gameobjects/mouse" + + +def game + $game +end class MyWindow < Gosu::Window def initialize super 640, 480, false - + $game = self self.caption = "Puit" - @objects = [] + @objects = [Mouse.new] end def update @objects.each_send :update end + + def draw + @objects.each_send :draw + end end -MyWindow.new.show +MyWindow.new + + +game.show \ No newline at end of file diff --git a/gameobjects/mouse.png b/gameobjects/mouse.png new file mode 100644 index 0000000..f5e1a06 Binary files /dev/null and b/gameobjects/mouse.png differ diff --git a/gameobjects/mouse.rb b/gameobjects/mouse.rb new file mode 100644 index 0000000..793e981 --- /dev/null +++ b/gameobjects/mouse.rb @@ -0,0 +1,2 @@ +class Mouse < Gameobject +end \ No newline at end of file diff --git a/lib/helpers.rb b/lib/helpers.rb index d751d05..cef3d0e 100644 --- a/lib/helpers.rb +++ b/lib/helpers.rb @@ -1,7 +1,82 @@ class Array def each_send what self.each do |e| e.send what end end -end \ No newline at end of file +end + + +class Object + def to_yml(f) + File.open(f, "w") do |e| + e.write self.to_yaml + end + self # return self so we can continue using that + end +end + + + +def load_image(name) + Gosu::Image.new(game, name) +end + +def scatter(measure) # @to named_fractions + randomly_between(-measure..measure) +end + + +class String + def png + file_name = self + $images ||= {} + $images[file_name] ||= Gosu::Image.new(game, file_name) + end + + def yml + $yaml ||= {} + $yaml[self] ||= YAML.load_file(self) rescue nil + end + + def from_yml + yml + end + + def draw(x,y,z) + file_name = self + $images ||= {} # level 1 ca$h + $images[file_name] ||= load_image(file_name) # level 2 ca$h ca$hed loaRDing + end + + def font(size=20) + cache_name = self + size.to_s + font_name = self + $fonts ||= {} + $fonts[cache_name] ||= Gosu::Font.new(game, font_name, size) + end + + def play() + cache_name = self + $songs ||= {} + $songs[cache_name] ||= Gosu::Sample.new($game, cache_name) + $songs[cache_name].play + end + + def require # full directory wide require + Dir.glob(self).sort.reverse.each do |e| + require e + end + end + + + def method_missing(method, *args) # and resend that method to that object + # INSTANT PWNZORING + # when unknown method, assume it an image or sound + # turns all strings into sound/image file system objects + $cache ||= {} + $cache[self] = Gosu::Image.new($game, self) rescue Gosu::Sample.new($game, self) + $cache[self].send method, args + # "resources/sprites/bla.png".draw(0,0) + end +end diff --git a/lib/spriter/gameobject.rb b/lib/spriter/gameobject.rb new file mode 100644 index 0000000..58987b0 --- /dev/null +++ b/lib/spriter/gameobject.rb @@ -0,0 +1,13 @@ +class Gameobject + def initialize + @sprite = "gameobjects/#{self.class.name.downcase}.png".png + # dir.glob classname + end + + def update + end + + def draw + @sprite.draw(0,0,0) + end +end \ No newline at end of file
oneup/Puit
56331058778d5f5c79648b700ee8ade691b661ab
window, objects
diff --git a/Gosu.icns b/Gosu.icns new file mode 100644 index 0000000..719acef Binary files /dev/null and b/Gosu.icns differ diff --git a/Main.rb b/Main.rb new file mode 100644 index 0000000..8d802a2 --- /dev/null +++ b/Main.rb @@ -0,0 +1,22 @@ +# Do not include gosu.bundle into this template. +# This is just here so you can run your game from the terminal, or +# your favorite text editor, using `ruby Main.rb`. + +require "rubygems" rescue nil +require 'gosu' +require "lib/helpers" + +class MyWindow < Gosu::Window + def initialize + super 640, 480, false + + self.caption = "Puit" + @objects = [] + end + + def update + @objects.each_send :update + end +end + +MyWindow.new.show diff --git a/lib/helpers.rb b/lib/helpers.rb new file mode 100644 index 0000000..d751d05 --- /dev/null +++ b/lib/helpers.rb @@ -0,0 +1,7 @@ +class Array + def each_send what + self.each do |e| + e.send what + end + end +end \ No newline at end of file
wilkerlucio/jquery-multiselect
011555713904017ee87fe34367b045e5001b7ba6
resizable input has a title attribute for hinting
diff --git a/js/jquery.multiselect.js b/js/jquery.multiselect.js index 8b21ae9..66584fb 100644 --- a/js/jquery.multiselect.js +++ b/js/jquery.multiselect.js @@ -1,525 +1,529 @@ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; (function($) { var KEY; KEY = { BACKSPACE: 8, TAB: 9, RETURN: 13, ESCAPE: 27, SPACE: 32, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, COLON: 188, DOT: 190 }; $.MultiSelect = (function() { function MultiSelect(element, options) { this.options = { separator: ",", completions: [], max_complete_results: 5, enable_new_options: true, complex_search: true, + title: null, afterChange: function() {}, afterAdd: function() {}, afterRemove: function() {} }; $.extend(this.options, options || {}); this.values = []; this.input = $(element); this.initialize_elements(); this.initialize_events(); this.parse_value(0, true); } MultiSelect.prototype.initialize_elements = function() { this.hidden = $(document.createElement("input")); this.hidden.attr("name", this.input.attr("name")); this.hidden.attr("type", "hidden"); this.input.removeAttr("name"); this.container = $(document.createElement("div")); this.container.addClass("jquery-multiselect"); this.input_wrapper = $(document.createElement("a")); this.input_wrapper.addClass("bit-input"); this.input.replaceWith(this.container); this.container.append(this.input_wrapper); this.input_wrapper.append(this.input); return this.container.before(this.hidden); }; MultiSelect.prototype.initialize_events = function() { this.selection = new $.MultiSelect.Selection(this.input); - this.resizable = new $.MultiSelect.ResizableInput(this.input); + this.resizable = new $.MultiSelect.ResizableInput(this.input, this.options.title); this.observer = new $.MultiSelect.InputObserver(this.input); this.autocomplete = new $.MultiSelect.AutoComplete(this, this.options.completions); this.input.click(__bind(function(e) { return e.stopPropagation(); }, this)); this.input.keyup(__bind(function() { return this.parse_value(1); }, this)); this.container.click(__bind(function() { this.input.focus(); return this.selection.set_caret_at_end(); }, this)); this.observer.bind([KEY.TAB, KEY.RETURN], __bind(function(e) { if (this.autocomplete.val()) { e.preventDefault(); return this.add_and_reset(); } }, this)); this.observer.bind([KEY.BACKSPACE], __bind(function(e) { var caret; if (this.values.length <= 0) { return; } caret = this.selection.get_caret(); if (caret[0] === 0 && caret[1] === 0) { e.preventDefault(); return this.remove(this.values[this.values.length - 1]); } }, this)); this.input.blur(__bind(function() { return setTimeout(__bind(function() { return this.autocomplete.hide_complete_box(); }, this), 200); }, this)); return this.observer.bind([KEY.ESCAPE], __bind(function(e) { return this.autocomplete.hide_complete_box(); }, this)); }; MultiSelect.prototype.values_real = function() { return $.map(this.values, function(v) { return v[1]; }); }; MultiSelect.prototype.parse_value = function(min, checkKey) { var label, value, values, _i, _len; if (min == null) { min = 0; } if (checkKey == null) { checkKey = false; } values = this.input.val().split(this.options.separator); if (values.length > min) { for (_i = 0, _len = values.length; _i < _len; _i++) { value = values[_i]; label = checkKey ? this.autocomplete.labelForValue(value) : value; if (value.present()) { this.add([label, value]); } } this.input.val(""); return this.autocomplete.search(); } }; MultiSelect.prototype.add_and_reset = function() { if (this.autocomplete.val()) { this.add(this.autocomplete.val()); this.input.val(""); return this.autocomplete.search(); } }; MultiSelect.prototype.add = function(value) { var a, close, oldValues; if ($.inArray(value[1], this.values_real()) > -1) { return; } if (value[0].blank()) { return; } value[1] = value[1].trim(); oldValues = this.values.slice(0); this.values.push(value); a = $(document.createElement("a")); a.addClass("bit bit-box"); a.mouseover(function() { return $(this).addClass("bit-hover"); }); a.mouseout(function() { return $(this).removeClass("bit-hover"); }); a.data("value", value); a.html(value[0].entitizeHTML()); close = $(document.createElement("a")); close.addClass("closebutton"); close.click(__bind(function() { return this.remove(a.data("value")); }, this)); a.append(close); this.input_wrapper.before(a); this.refresh_hidden(); this.options.afterAdd(this, value); return this.options.afterChange(this, oldValues); }; MultiSelect.prototype.remove = function(value) { var oldValues; oldValues = this.values.slice(0); this.values = $.grep(this.values, function(v) { return v[1] !== value[1]; }); this.container.find("a.bit-box").each(function() { if ($(this).data("value")[1] === value[1]) { return $(this).remove(); } }); this.refresh_hidden(); this.options.afterRemove(this, value); return this.options.afterChange(this, oldValues); }; MultiSelect.prototype.refresh_hidden = function() { return this.hidden.val(this.values_real().join(this.options.separator)); }; return MultiSelect; })(); $.MultiSelect.InputObserver = (function() { function InputObserver(element) { this.input = $(element); this.input.keydown(__bind(function(e) { return this.handle_keydown(e); }, this)); this.events = []; } InputObserver.prototype.bind = function(key, callback) { return this.events.push([key, callback]); }; InputObserver.prototype.handle_keydown = function(e) { var callback, event, keys, _i, _len, _ref, _results; _ref = this.events; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { event = _ref[_i]; keys = event[0], callback = event[1]; if (!keys.push) { keys = [keys]; } _results.push($.inArray(e.keyCode, keys) > -1 ? callback(e) : void 0); } return _results; }; return InputObserver; })(); $.MultiSelect.Selection = (function() { function Selection(element) { this.input = $(element)[0]; } Selection.prototype.get_caret = function() { var r; if (document.selection) { r = document.selection.createRange().duplicate(); r.moveEnd('character', this.input.value.length); if (r.text === '') { return [this.input.value.length, this.input.value.length]; } else { return [this.input.value.lastIndexOf(r.text), this.input.value.lastIndexOf(r.text)]; } } else { return [this.input.selectionStart, this.input.selectionEnd]; } }; Selection.prototype.set_caret = function(begin, end) { end != null ? end : end = begin; this.input.selectionStart = begin; return this.input.selectionEnd = end; }; Selection.prototype.set_caret_at_end = function() { return this.set_caret(this.input.value.length); }; return Selection; })(); $.MultiSelect.ResizableInput = (function() { - function ResizableInput(element) { + function ResizableInput(element, title) { this.input = $(element); + if (title) { + this.input.attr('title', title); + } this.create_measurer(); this.input.keypress(__bind(function(e) { return this.set_width(e); }, this)); this.input.keyup(__bind(function(e) { return this.set_width(e); }, this)); this.input.change(__bind(function(e) { return this.set_width(e); }, this)); } ResizableInput.prototype.create_measurer = function() { var measurer; if ($("#__jquery_multiselect_measurer")[0] === void 0) { measurer = $(document.createElement("div")); measurer.attr("id", "__jquery_multiselect_measurer"); measurer.css({ position: "absolute", left: "-1000px", top: "-1000px" }); $(document.body).append(measurer); } this.measurer = $("#__jquery_multiselect_measurer:first"); return this.measurer.css({ fontSize: this.input.css('font-size'), fontFamily: this.input.css('font-family') }); }; ResizableInput.prototype.calculate_width = function() { this.measurer.html(this.input.val().entitizeHTML() + 'MM'); return this.measurer.innerWidth(); }; ResizableInput.prototype.set_width = function() { return this.input.css("width", this.calculate_width() + "px"); }; return ResizableInput; })(); $.MultiSelect.AutoComplete = (function() { function AutoComplete(multiselect, completions) { this.multiselect = multiselect; this.input = this.multiselect.input; this.completions = this.parse_completions(completions); this.matches = []; this.create_elements(); this.bind_events(); } AutoComplete.prototype.parse_completions = function(completions) { return $.map(completions, function(value) { if (typeof value === "string") { return [[value, value]]; } else if (value instanceof Array && value.length === 2) { return [value]; } else if (value.value && value.caption) { return [[value.caption, value.value]]; } else { if (console) { return console.error("Invalid option " + value); } } }); }; AutoComplete.prototype.labelForValue = function(value) { var completion, label, val, _i, _len, _ref; _ref = this.completions; for (_i = 0, _len = _ref.length; _i < _len; _i++) { completion = _ref[_i]; label = completion[0], val = completion[1]; if (val === value) { return label; } } return value; }; AutoComplete.prototype.create_elements = function() { this.container = $(document.createElement("div")); this.container.addClass("jquery-multiselect-autocomplete"); this.container.css("width", this.multiselect.container.outerWidth()); this.container.css("display", "none"); this.container.append(this.def); this.list = $(document.createElement("ul")); this.list.addClass("feed"); this.container.append(this.list); return this.multiselect.container.after(this.container); }; AutoComplete.prototype.bind_events = function() { this.input.keypress(__bind(function(e) { return this.search(e); }, this)); this.input.keyup(__bind(function(e) { return this.search(e); }, this)); this.input.change(__bind(function(e) { return this.search(e); }, this)); this.multiselect.observer.bind(KEY.UP, __bind(function(e) { e.preventDefault(); return this.navigate_up(); }, this)); return this.multiselect.observer.bind(KEY.DOWN, __bind(function(e) { e.preventDefault(); return this.navigate_down(); }, this)); }; AutoComplete.prototype.search = function() { var def, i, item, option, x, _len, _ref; if (this.input.val().trim() === this.query) { return; } this.query = this.input.val().trim(); this.list.html(""); this.current = 0; if (this.query.present()) { this.container.fadeIn("fast"); this.matches = this.matching_completions(this.query); if (this.multiselect.options.enable_new_options) { def = this.create_item("Add <em>" + this.query + "</em>"); def.mouseover(__bind(function(e) { return this.select_index(0); }, this)); } _ref = this.matches; for (i = 0, _len = _ref.length; i < _len; i++) { option = _ref[i]; x = this.multiselect.options.enable_new_options ? i + 1 : i; item = this.create_item(this.highlight(option[0], this.query)); item.mouseover(__bind(function(e) { return this.select_index(x); }, this)); } if (this.multiselect.options.enable_new_options) { this.matches.unshift([this.query, this.query]); } return this.select_index(0); } else { this.matches = []; this.hide_complete_box(); return this.query = null; } }; AutoComplete.prototype.hide_complete_box = function() { return this.container.fadeOut("fast"); }; AutoComplete.prototype.select_index = function(index) { var items; items = this.list.find("li"); items.removeClass("auto-focus"); items.filter(":eq(" + index + ")").addClass("auto-focus"); return this.current = index; }; AutoComplete.prototype.navigate_down = function() { var next; next = this.current + 1; if (next >= this.matches.length) { next = 0; } return this.select_index(next); }; AutoComplete.prototype.navigate_up = function() { var next; next = this.current - 1; if (next < 0) { next = this.matches.length - 1; } return this.select_index(next); }; AutoComplete.prototype.create_item = function(text, highlight) { var item; item = $(document.createElement("li")); item.click(__bind(function() { this.multiselect.add_and_reset(); this.search(); return this.input.focus(); }, this)); item.html(text); this.list.append(item); return item; }; AutoComplete.prototype.val = function() { return this.matches[this.current]; }; AutoComplete.prototype.highlight = function(text, highlight) { var char, current, highlighted, i, reg, _len; if (this.multiselect.options.complex_search) { highlighted = ""; current = 0; for (i = 0, _len = text.length; i < _len; i++) { char = text[i]; char = text.charAt(i); if (current < highlight.length && char.toLowerCase() === highlight.charAt(current).toLowerCase()) { highlighted += "<em>" + char + "</em>"; current++; } else { highlighted += char; } } return highlighted; } else { reg = "(" + (RegExp.escape(highlight)) + ")"; return text.replace(new RegExp(reg, "gi"), '<em>$1</em>'); } }; AutoComplete.prototype.matching_completions = function(text) { var char, count, i, reg, _len; if (this.multiselect.options.complex_search) { reg = ""; for (i = 0, _len = text.length; i < _len; i++) { char = text[i]; char = text.charAt(i); reg += RegExp.escape(char) + ".*"; } reg = new RegExp(reg, "i"); } else { reg = new RegExp(RegExp.escape(text), "i"); } count = 0; return $.grep(this.completions, __bind(function(c) { if (count >= this.multiselect.options.max_complete_results) { return false; } if ($.inArray(c[1], this.multiselect.values_real()) > -1) { return false; } if (c[0].match(reg)) { count++; return true; } else { return false; } }, this)); }; return AutoComplete; })(); $.fn.multiselect = function(options) { options != null ? options : options = {}; return $(this).each(function() { var add, completions, input, multiselect, option, select_options, val, _i, _j, _len, _len2, _ref; if (this.tagName.toLowerCase() === "select") { input = $(document.createElement("input")); input.attr("type", "text"); input.attr("name", this.name); input.attr("id", this.id); completions = []; add = []; _ref = this.options; for (_i = 0, _len = _ref.length; _i < _len; _i++) { option = _ref[_i]; completions.push([option.innerHTML, option.value]); if (option.selected) { add.push([option.innerHTML, option.value]); } } select_options = { completions: completions, enable_new_options: false }; $.extend(select_options, options); $(this).replaceWith(input); multiselect = new $.MultiSelect(input, select_options); for (_j = 0, _len2 = add.length; _j < _len2; _j++) { val = add[_j]; multiselect.add(val); } return multiselect; } else if (this.tagName.toLowerCase() === "input" && this.type === "text") { return new $.MultiSelect(this, options); } }); }; $.extend(String.prototype, { trim: function() { return this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, ''); }, entitizeHTML: function() { return this.replace(/</g, '&lt;').replace(/>/g, '&gt;'); }, unentitizeHTML: function() { return this.replace(/&lt;/g, '<').replace(/&gt;/g, '>'); }, blank: function() { return this.trim().length === 0; }, present: function() { return !this.blank(); } }); return RegExp.escape = function(str) { return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); }; })(jQuery); }).call(this); diff --git a/src/jquery.multiselect.coffee b/src/jquery.multiselect.coffee index 3568251..d61cd5c 100644 --- a/src/jquery.multiselect.coffee +++ b/src/jquery.multiselect.coffee @@ -1,447 +1,449 @@ # Copyright (c) 2010 Wilker Lúcio # # 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. (($) -> KEY = { BACKSPACE: 8 TAB: 9 RETURN: 13 ESCAPE: 27 SPACE: 32 LEFT: 37 UP: 38 RIGHT: 39 DOWN: 40 COLON: 188 DOT: 190 } class $.MultiSelect constructor: (element, options) -> @options = { # options separator: "," completions: [] max_complete_results: 5 enable_new_options: true complex_search: true + title: null # callbacks afterChange: -> afterAdd: -> afterRemove: -> } $.extend(@options, options || {}) @values = [] @input = $(element) @initialize_elements() @initialize_events() @parse_value(0, true) initialize_elements: -> # hidden input to hold real value @hidden = $(document.createElement("input")) @hidden.attr("name", @input.attr("name")) @hidden.attr("type", "hidden") @input.removeAttr("name") @container = $(document.createElement("div")) @container.addClass("jquery-multiselect") @input_wrapper = $(document.createElement("a")) @input_wrapper.addClass("bit-input") @input.replaceWith(@container) @container.append(@input_wrapper) @input_wrapper.append(@input) @container.before(@hidden) initialize_events: -> # create helpers @selection = new $.MultiSelect.Selection(@input) - @resizable = new $.MultiSelect.ResizableInput(@input) + @resizable = new $.MultiSelect.ResizableInput(@input, @options.title) @observer = new $.MultiSelect.InputObserver(@input) @autocomplete = new $.MultiSelect.AutoComplete(this, @options.completions) # prevent container click to put carret at end @input.click (e) => e.stopPropagation() # create element when place separator or paste @input.keyup => @parse_value(1) # focus input and set carret at and @container.click => @input.focus() @selection.set_caret_at_end() # add element on press TAB or RETURN @observer.bind [KEY.TAB, KEY.RETURN], (e) => if @autocomplete.val() e.preventDefault() @add_and_reset() # remove last item @observer.bind [KEY.BACKSPACE], (e) => return if @values.length <= 0 caret = @selection.get_caret() if caret[0] == 0 and caret[1] == 0 e.preventDefault() @remove(@values[@values.length - 1]) # hide complete box @input.blur => setTimeout(=> @autocomplete.hide_complete_box() 200) @observer.bind [KEY.ESCAPE], (e) => @autocomplete.hide_complete_box() values_real: -> $.map @values, (v) -> v[1] parse_value: (min = 0, checkKey = false) -> values = @input.val().split(@options.separator) if values.length > min for value in values label = if checkKey then @autocomplete.labelForValue(value) else value @add [label, value] if value.present() @input.val("") @autocomplete.search() add_and_reset: -> if @autocomplete.val() @add(@autocomplete.val()) @input.val("") @autocomplete.search() # add new element add: (value) -> return if $.inArray(value[1], @values_real()) > -1 return if value[0].blank() value[1] = value[1].trim() oldValues = @values.slice(0) @values.push(value) a = $(document.createElement("a")) a.addClass("bit bit-box") a.mouseover -> $(this).addClass("bit-hover") a.mouseout -> $(this).removeClass("bit-hover") a.data("value", value) a.html(value[0].entitizeHTML()) close = $(document.createElement("a")) close.addClass("closebutton") close.click => @remove(a.data("value")) a.append(close) @input_wrapper.before(a) @refresh_hidden() @options.afterAdd(this, value) @options.afterChange(this, oldValues) remove: (value) -> oldValues = @values.slice(0) @values = $.grep @values, (v) -> v[1] != value[1] @container.find("a.bit-box").each -> $(this).remove() if $(this).data("value")[1] == value[1] @refresh_hidden() @options.afterRemove(this, value) @options.afterChange(this, oldValues) refresh_hidden: -> @hidden.val(@values_real().join(@options.separator)) # Input Observer Helper class $.MultiSelect.InputObserver constructor: (element) -> @input = $(element) @input.keydown (e) => @handle_keydown(e) @events = [] bind: (key, callback) -> @events.push([key, callback]) handle_keydown: (e) -> for event in @events [keys, callback] = event keys = [keys] unless keys.push callback(e) if $.inArray(e.keyCode, keys) > -1 # Selection Helper class $.MultiSelect.Selection constructor: (element) -> @input = $(element)[0] get_caret: -> # For IE if document.selection r = document.selection.createRange().duplicate() r.moveEnd('character', @input.value.length) if r.text == '' [@input.value.length, @input.value.length] else [@input.value.lastIndexOf(r.text), @input.value.lastIndexOf(r.text)] # Others else [@input.selectionStart, @input.selectionEnd] set_caret: (begin, end) -> end ?= begin @input.selectionStart = begin @input.selectionEnd = end set_caret_at_end: -> @set_caret(@input.value.length) # Resizable Input Helper class $.MultiSelect.ResizableInput - constructor: (element) -> + constructor: (element, title) -> @input = $(element) + @input.attr('title', title) if title @create_measurer() @input.keypress (e) => @set_width(e) @input.keyup (e) => @set_width(e) @input.change (e) => @set_width(e) create_measurer: -> if $("#__jquery_multiselect_measurer")[0] == undefined measurer = $(document.createElement("div")) measurer.attr("id", "__jquery_multiselect_measurer") measurer.css { position: "absolute" left: "-1000px" top: "-1000px" } $(document.body).append(measurer) @measurer = $("#__jquery_multiselect_measurer:first") @measurer.css { fontSize: @input.css('font-size') fontFamily: @input.css('font-family') } calculate_width: -> @measurer.html(@input.val().entitizeHTML() + 'MM') @measurer.innerWidth() set_width: -> @input.css("width", @calculate_width() + "px") # AutoComplete Helper class $.MultiSelect.AutoComplete constructor: (multiselect, completions) -> @multiselect = multiselect @input = @multiselect.input @completions = @parse_completions(completions) @matches = [] @create_elements() @bind_events() parse_completions: (completions) -> $.map completions, (value) -> if typeof value == "string" [[value, value]] else if value instanceof Array and value.length == 2 [value] else if value.value and value.caption [[value.caption, value.value]] else console.error "Invalid option #{value}" if console labelForValue: (value) -> for completion in @completions [label, val] = completion return label if val == value value create_elements: -> @container = $(document.createElement("div")) @container.addClass("jquery-multiselect-autocomplete") @container.css("width", @multiselect.container.outerWidth()) @container.css("display", "none") @container.append(@def) @list = $(document.createElement("ul")) @list.addClass("feed") @container.append(@list) @multiselect.container.after(@container) bind_events: -> @input.keypress (e) => @search(e) @input.keyup (e) => @search(e) @input.change (e) => @search(e) @multiselect.observer.bind KEY.UP, (e) => e.preventDefault(); @navigate_up() @multiselect.observer.bind KEY.DOWN, (e) => e.preventDefault(); @navigate_down() search: -> return if @input.val().trim() == @query # dont do operation if query is same @query = @input.val().trim() @list.html("") # clear list @current = 0 if @query.present() @container.fadeIn("fast") @matches = @matching_completions(@query) if @multiselect.options.enable_new_options def = @create_item("Add <em>" + @query + "</em>") def.mouseover (e) => @select_index(0) for option, i in @matches x = if @multiselect.options.enable_new_options then i + 1 else i item = @create_item(@highlight(option[0], @query)) item.mouseover (e) => @select_index(x) @matches.unshift([@query, @query]) if @multiselect.options.enable_new_options @select_index(0) else @matches = [] @hide_complete_box() @query = null hide_complete_box: -> @container.fadeOut("fast") select_index: (index) -> items = @list.find("li") items.removeClass("auto-focus") items.filter(":eq(#{index})").addClass("auto-focus") @current = index navigate_down: -> next = @current + 1 next = 0 if next >= @matches.length @select_index(next) navigate_up: -> next = @current - 1 next = @matches.length - 1 if next < 0 @select_index(next) create_item: (text, highlight) -> item = $(document.createElement("li")) item.click => @multiselect.add_and_reset() @search() @input.focus() item.html(text) @list.append(item) item val: -> @matches[@current] highlight: (text, highlight) -> if @multiselect.options.complex_search highlighted = "" current = 0 for char, i in text char = text.charAt(i) if current < highlight.length and char.toLowerCase() == highlight.charAt(current).toLowerCase() highlighted += "<em>#{char}</em>" current++ else highlighted += char highlighted else reg = "(#{RegExp.escape(highlight)})" text.replace(new RegExp(reg, "gi"), '<em>$1</em>') matching_completions: (text) -> if @multiselect.options.complex_search reg = "" for char, i in text char = text.charAt(i) reg += RegExp.escape(char) + ".*" reg = new RegExp(reg, "i") else reg = new RegExp(RegExp.escape(text), "i") count = 0 $.grep @completions, (c) => return false if count >= @multiselect.options.max_complete_results return false if $.inArray(c[1], @multiselect.values_real()) > -1 if c[0].match(reg) count++ true else false # Hook jQuery extension $.fn.multiselect = (options) -> options ?= {} $(this).each -> if this.tagName.toLowerCase() == "select" input = $(document.createElement("input")) input.attr("type", "text") input.attr("name", this.name) input.attr("id", this.id) completions = [] add = [] for option in this.options completions.push([option.innerHTML, option.value]) add.push([option.innerHTML, option.value]) if option.selected select_options = { completions: completions enable_new_options: false } $.extend(select_options, options) $(this).replaceWith(input) multiselect = new $.MultiSelect(input, select_options) multiselect.add(val) for val in add multiselect else if this.tagName.toLowerCase() == "input" and this.type == "text" new $.MultiSelect(this, options) $.extend String.prototype, { trim: -> this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, '') entitizeHTML: -> this.replace(/</g,'&lt;').replace(/>/g,'&gt;') unentitizeHTML: -> this.replace(/&lt;/g,'<').replace(/&gt;/g,'>') blank: -> this.trim().length == 0 present: -> not @blank() } RegExp.escape = (str) -> String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1') )(jQuery)
wilkerlucio/jquery-multiselect
0a62ee271943de8c722b5e85d6bb637d796aadd9
added some events
diff --git a/js/jquery.multiselect.js b/js/jquery.multiselect.js index baa374b..8b21ae9 100644 --- a/js/jquery.multiselect.js +++ b/js/jquery.multiselect.js @@ -1,515 +1,525 @@ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; (function($) { var KEY; KEY = { BACKSPACE: 8, TAB: 9, RETURN: 13, ESCAPE: 27, SPACE: 32, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, COLON: 188, DOT: 190 }; $.MultiSelect = (function() { function MultiSelect(element, options) { this.options = { separator: ",", completions: [], max_complete_results: 5, enable_new_options: true, - complex_search: true + complex_search: true, + afterChange: function() {}, + afterAdd: function() {}, + afterRemove: function() {} }; $.extend(this.options, options || {}); this.values = []; this.input = $(element); this.initialize_elements(); this.initialize_events(); this.parse_value(0, true); } MultiSelect.prototype.initialize_elements = function() { this.hidden = $(document.createElement("input")); this.hidden.attr("name", this.input.attr("name")); this.hidden.attr("type", "hidden"); this.input.removeAttr("name"); this.container = $(document.createElement("div")); this.container.addClass("jquery-multiselect"); this.input_wrapper = $(document.createElement("a")); this.input_wrapper.addClass("bit-input"); this.input.replaceWith(this.container); this.container.append(this.input_wrapper); this.input_wrapper.append(this.input); return this.container.before(this.hidden); }; MultiSelect.prototype.initialize_events = function() { this.selection = new $.MultiSelect.Selection(this.input); this.resizable = new $.MultiSelect.ResizableInput(this.input); this.observer = new $.MultiSelect.InputObserver(this.input); this.autocomplete = new $.MultiSelect.AutoComplete(this, this.options.completions); this.input.click(__bind(function(e) { return e.stopPropagation(); }, this)); this.input.keyup(__bind(function() { return this.parse_value(1); }, this)); this.container.click(__bind(function() { this.input.focus(); return this.selection.set_caret_at_end(); }, this)); this.observer.bind([KEY.TAB, KEY.RETURN], __bind(function(e) { if (this.autocomplete.val()) { e.preventDefault(); return this.add_and_reset(); } }, this)); this.observer.bind([KEY.BACKSPACE], __bind(function(e) { var caret; if (this.values.length <= 0) { return; } caret = this.selection.get_caret(); if (caret[0] === 0 && caret[1] === 0) { e.preventDefault(); return this.remove(this.values[this.values.length - 1]); } }, this)); this.input.blur(__bind(function() { return setTimeout(__bind(function() { return this.autocomplete.hide_complete_box(); }, this), 200); }, this)); return this.observer.bind([KEY.ESCAPE], __bind(function(e) { return this.autocomplete.hide_complete_box(); }, this)); }; MultiSelect.prototype.values_real = function() { return $.map(this.values, function(v) { return v[1]; }); }; MultiSelect.prototype.parse_value = function(min, checkKey) { var label, value, values, _i, _len; if (min == null) { min = 0; } if (checkKey == null) { checkKey = false; } values = this.input.val().split(this.options.separator); if (values.length > min) { for (_i = 0, _len = values.length; _i < _len; _i++) { value = values[_i]; label = checkKey ? this.autocomplete.labelForValue(value) : value; if (value.present()) { this.add([label, value]); } } this.input.val(""); return this.autocomplete.search(); } }; MultiSelect.prototype.add_and_reset = function() { if (this.autocomplete.val()) { this.add(this.autocomplete.val()); this.input.val(""); return this.autocomplete.search(); } }; MultiSelect.prototype.add = function(value) { - var a, close; + var a, close, oldValues; if ($.inArray(value[1], this.values_real()) > -1) { return; } if (value[0].blank()) { return; } value[1] = value[1].trim(); + oldValues = this.values.slice(0); this.values.push(value); a = $(document.createElement("a")); a.addClass("bit bit-box"); a.mouseover(function() { return $(this).addClass("bit-hover"); }); a.mouseout(function() { return $(this).removeClass("bit-hover"); }); a.data("value", value); a.html(value[0].entitizeHTML()); close = $(document.createElement("a")); close.addClass("closebutton"); close.click(__bind(function() { return this.remove(a.data("value")); }, this)); a.append(close); this.input_wrapper.before(a); - return this.refresh_hidden(); + this.refresh_hidden(); + this.options.afterAdd(this, value); + return this.options.afterChange(this, oldValues); }; MultiSelect.prototype.remove = function(value) { + var oldValues; + oldValues = this.values.slice(0); this.values = $.grep(this.values, function(v) { return v[1] !== value[1]; }); this.container.find("a.bit-box").each(function() { if ($(this).data("value")[1] === value[1]) { return $(this).remove(); } }); - return this.refresh_hidden(); + this.refresh_hidden(); + this.options.afterRemove(this, value); + return this.options.afterChange(this, oldValues); }; MultiSelect.prototype.refresh_hidden = function() { return this.hidden.val(this.values_real().join(this.options.separator)); }; return MultiSelect; })(); $.MultiSelect.InputObserver = (function() { function InputObserver(element) { this.input = $(element); this.input.keydown(__bind(function(e) { return this.handle_keydown(e); }, this)); this.events = []; } InputObserver.prototype.bind = function(key, callback) { return this.events.push([key, callback]); }; InputObserver.prototype.handle_keydown = function(e) { var callback, event, keys, _i, _len, _ref, _results; _ref = this.events; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { event = _ref[_i]; keys = event[0], callback = event[1]; if (!keys.push) { keys = [keys]; } _results.push($.inArray(e.keyCode, keys) > -1 ? callback(e) : void 0); } return _results; }; return InputObserver; })(); $.MultiSelect.Selection = (function() { function Selection(element) { this.input = $(element)[0]; } Selection.prototype.get_caret = function() { var r; if (document.selection) { r = document.selection.createRange().duplicate(); r.moveEnd('character', this.input.value.length); if (r.text === '') { return [this.input.value.length, this.input.value.length]; } else { return [this.input.value.lastIndexOf(r.text), this.input.value.lastIndexOf(r.text)]; } } else { return [this.input.selectionStart, this.input.selectionEnd]; } }; Selection.prototype.set_caret = function(begin, end) { end != null ? end : end = begin; this.input.selectionStart = begin; return this.input.selectionEnd = end; }; Selection.prototype.set_caret_at_end = function() { return this.set_caret(this.input.value.length); }; return Selection; })(); $.MultiSelect.ResizableInput = (function() { function ResizableInput(element) { this.input = $(element); this.create_measurer(); this.input.keypress(__bind(function(e) { return this.set_width(e); }, this)); this.input.keyup(__bind(function(e) { return this.set_width(e); }, this)); this.input.change(__bind(function(e) { return this.set_width(e); }, this)); } ResizableInput.prototype.create_measurer = function() { var measurer; if ($("#__jquery_multiselect_measurer")[0] === void 0) { measurer = $(document.createElement("div")); measurer.attr("id", "__jquery_multiselect_measurer"); measurer.css({ position: "absolute", left: "-1000px", top: "-1000px" }); $(document.body).append(measurer); } this.measurer = $("#__jquery_multiselect_measurer:first"); return this.measurer.css({ fontSize: this.input.css('font-size'), fontFamily: this.input.css('font-family') }); }; ResizableInput.prototype.calculate_width = function() { this.measurer.html(this.input.val().entitizeHTML() + 'MM'); return this.measurer.innerWidth(); }; ResizableInput.prototype.set_width = function() { return this.input.css("width", this.calculate_width() + "px"); }; return ResizableInput; })(); $.MultiSelect.AutoComplete = (function() { function AutoComplete(multiselect, completions) { this.multiselect = multiselect; this.input = this.multiselect.input; this.completions = this.parse_completions(completions); this.matches = []; this.create_elements(); this.bind_events(); } AutoComplete.prototype.parse_completions = function(completions) { return $.map(completions, function(value) { if (typeof value === "string") { return [[value, value]]; } else if (value instanceof Array && value.length === 2) { return [value]; } else if (value.value && value.caption) { return [[value.caption, value.value]]; } else { if (console) { return console.error("Invalid option " + value); } } }); }; AutoComplete.prototype.labelForValue = function(value) { var completion, label, val, _i, _len, _ref; _ref = this.completions; for (_i = 0, _len = _ref.length; _i < _len; _i++) { completion = _ref[_i]; label = completion[0], val = completion[1]; if (val === value) { return label; } } return value; }; AutoComplete.prototype.create_elements = function() { this.container = $(document.createElement("div")); this.container.addClass("jquery-multiselect-autocomplete"); this.container.css("width", this.multiselect.container.outerWidth()); this.container.css("display", "none"); this.container.append(this.def); this.list = $(document.createElement("ul")); this.list.addClass("feed"); this.container.append(this.list); return this.multiselect.container.after(this.container); }; AutoComplete.prototype.bind_events = function() { this.input.keypress(__bind(function(e) { return this.search(e); }, this)); this.input.keyup(__bind(function(e) { return this.search(e); }, this)); this.input.change(__bind(function(e) { return this.search(e); }, this)); this.multiselect.observer.bind(KEY.UP, __bind(function(e) { e.preventDefault(); return this.navigate_up(); }, this)); return this.multiselect.observer.bind(KEY.DOWN, __bind(function(e) { e.preventDefault(); return this.navigate_down(); }, this)); }; AutoComplete.prototype.search = function() { var def, i, item, option, x, _len, _ref; if (this.input.val().trim() === this.query) { return; } this.query = this.input.val().trim(); this.list.html(""); this.current = 0; if (this.query.present()) { this.container.fadeIn("fast"); this.matches = this.matching_completions(this.query); if (this.multiselect.options.enable_new_options) { def = this.create_item("Add <em>" + this.query + "</em>"); def.mouseover(__bind(function(e) { return this.select_index(0); }, this)); } _ref = this.matches; for (i = 0, _len = _ref.length; i < _len; i++) { option = _ref[i]; x = this.multiselect.options.enable_new_options ? i + 1 : i; item = this.create_item(this.highlight(option[0], this.query)); item.mouseover(__bind(function(e) { return this.select_index(x); }, this)); } if (this.multiselect.options.enable_new_options) { this.matches.unshift([this.query, this.query]); } return this.select_index(0); } else { this.matches = []; this.hide_complete_box(); return this.query = null; } }; AutoComplete.prototype.hide_complete_box = function() { return this.container.fadeOut("fast"); }; AutoComplete.prototype.select_index = function(index) { var items; items = this.list.find("li"); items.removeClass("auto-focus"); items.filter(":eq(" + index + ")").addClass("auto-focus"); return this.current = index; }; AutoComplete.prototype.navigate_down = function() { var next; next = this.current + 1; if (next >= this.matches.length) { next = 0; } return this.select_index(next); }; AutoComplete.prototype.navigate_up = function() { var next; next = this.current - 1; if (next < 0) { next = this.matches.length - 1; } return this.select_index(next); }; AutoComplete.prototype.create_item = function(text, highlight) { var item; item = $(document.createElement("li")); item.click(__bind(function() { this.multiselect.add_and_reset(); this.search(); return this.input.focus(); }, this)); item.html(text); this.list.append(item); return item; }; AutoComplete.prototype.val = function() { return this.matches[this.current]; }; AutoComplete.prototype.highlight = function(text, highlight) { var char, current, highlighted, i, reg, _len; if (this.multiselect.options.complex_search) { highlighted = ""; current = 0; for (i = 0, _len = text.length; i < _len; i++) { char = text[i]; char = text.charAt(i); if (current < highlight.length && char.toLowerCase() === highlight.charAt(current).toLowerCase()) { highlighted += "<em>" + char + "</em>"; current++; } else { highlighted += char; } } return highlighted; } else { reg = "(" + (RegExp.escape(highlight)) + ")"; return text.replace(new RegExp(reg, "gi"), '<em>$1</em>'); } }; AutoComplete.prototype.matching_completions = function(text) { var char, count, i, reg, _len; if (this.multiselect.options.complex_search) { reg = ""; for (i = 0, _len = text.length; i < _len; i++) { char = text[i]; char = text.charAt(i); reg += RegExp.escape(char) + ".*"; } reg = new RegExp(reg, "i"); } else { reg = new RegExp(RegExp.escape(text), "i"); } count = 0; return $.grep(this.completions, __bind(function(c) { if (count >= this.multiselect.options.max_complete_results) { return false; } if ($.inArray(c[1], this.multiselect.values_real()) > -1) { return false; } if (c[0].match(reg)) { count++; return true; } else { return false; } }, this)); }; return AutoComplete; })(); $.fn.multiselect = function(options) { options != null ? options : options = {}; return $(this).each(function() { var add, completions, input, multiselect, option, select_options, val, _i, _j, _len, _len2, _ref; if (this.tagName.toLowerCase() === "select") { input = $(document.createElement("input")); input.attr("type", "text"); input.attr("name", this.name); input.attr("id", this.id); completions = []; add = []; _ref = this.options; for (_i = 0, _len = _ref.length; _i < _len; _i++) { option = _ref[_i]; completions.push([option.innerHTML, option.value]); if (option.selected) { add.push([option.innerHTML, option.value]); } } select_options = { completions: completions, enable_new_options: false }; $.extend(select_options, options); $(this).replaceWith(input); multiselect = new $.MultiSelect(input, select_options); for (_j = 0, _len2 = add.length; _j < _len2; _j++) { val = add[_j]; multiselect.add(val); } return multiselect; } else if (this.tagName.toLowerCase() === "input" && this.type === "text") { return new $.MultiSelect(this, options); } }); }; $.extend(String.prototype, { trim: function() { return this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, ''); }, entitizeHTML: function() { return this.replace(/</g, '&lt;').replace(/>/g, '&gt;'); }, unentitizeHTML: function() { return this.replace(/&lt;/g, '<').replace(/&gt;/g, '>'); }, blank: function() { return this.trim().length === 0; }, present: function() { return !this.blank(); } }); return RegExp.escape = function(str) { return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); }; })(jQuery); }).call(this); diff --git a/src/jquery.multiselect.coffee b/src/jquery.multiselect.coffee index a667b2f..3568251 100644 --- a/src/jquery.multiselect.coffee +++ b/src/jquery.multiselect.coffee @@ -1,431 +1,447 @@ # Copyright (c) 2010 Wilker Lúcio # # 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. (($) -> KEY = { BACKSPACE: 8 - TAB: 9 - RETURN: 13 - ESCAPE: 27 - SPACE: 32 - LEFT: 37 - UP: 38 - RIGHT: 39 - DOWN: 40 - COLON: 188 - DOT: 190 + TAB: 9 + RETURN: 13 + ESCAPE: 27 + SPACE: 32 + LEFT: 37 + UP: 38 + RIGHT: 39 + DOWN: 40 + COLON: 188 + DOT: 190 } class $.MultiSelect constructor: (element, options) -> @options = { - separator: "," - completions: [] + # options + separator: "," + completions: [] max_complete_results: 5 - enable_new_options: true - complex_search: true + enable_new_options: true + complex_search: true + + # callbacks + afterChange: -> + afterAdd: -> + afterRemove: -> } + $.extend(@options, options || {}) @values = [] @input = $(element) @initialize_elements() @initialize_events() @parse_value(0, true) initialize_elements: -> # hidden input to hold real value @hidden = $(document.createElement("input")) @hidden.attr("name", @input.attr("name")) @hidden.attr("type", "hidden") @input.removeAttr("name") @container = $(document.createElement("div")) @container.addClass("jquery-multiselect") @input_wrapper = $(document.createElement("a")) @input_wrapper.addClass("bit-input") @input.replaceWith(@container) @container.append(@input_wrapper) @input_wrapper.append(@input) @container.before(@hidden) initialize_events: -> # create helpers @selection = new $.MultiSelect.Selection(@input) @resizable = new $.MultiSelect.ResizableInput(@input) @observer = new $.MultiSelect.InputObserver(@input) @autocomplete = new $.MultiSelect.AutoComplete(this, @options.completions) # prevent container click to put carret at end @input.click (e) => e.stopPropagation() # create element when place separator or paste @input.keyup => @parse_value(1) # focus input and set carret at and @container.click => @input.focus() @selection.set_caret_at_end() # add element on press TAB or RETURN @observer.bind [KEY.TAB, KEY.RETURN], (e) => if @autocomplete.val() e.preventDefault() @add_and_reset() # remove last item @observer.bind [KEY.BACKSPACE], (e) => return if @values.length <= 0 caret = @selection.get_caret() if caret[0] == 0 and caret[1] == 0 e.preventDefault() @remove(@values[@values.length - 1]) # hide complete box @input.blur => setTimeout(=> @autocomplete.hide_complete_box() 200) @observer.bind [KEY.ESCAPE], (e) => @autocomplete.hide_complete_box() values_real: -> $.map @values, (v) -> v[1] parse_value: (min = 0, checkKey = false) -> values = @input.val().split(@options.separator) if values.length > min for value in values label = if checkKey then @autocomplete.labelForValue(value) else value @add [label, value] if value.present() @input.val("") @autocomplete.search() add_and_reset: -> if @autocomplete.val() @add(@autocomplete.val()) @input.val("") @autocomplete.search() # add new element add: (value) -> return if $.inArray(value[1], @values_real()) > -1 return if value[0].blank() value[1] = value[1].trim() + oldValues = @values.slice(0) @values.push(value) a = $(document.createElement("a")) a.addClass("bit bit-box") a.mouseover -> $(this).addClass("bit-hover") a.mouseout -> $(this).removeClass("bit-hover") a.data("value", value) a.html(value[0].entitizeHTML()) close = $(document.createElement("a")) close.addClass("closebutton") close.click => @remove(a.data("value")) a.append(close) @input_wrapper.before(a) @refresh_hidden() + @options.afterAdd(this, value) + @options.afterChange(this, oldValues) + remove: (value) -> + oldValues = @values.slice(0) + @values = $.grep @values, (v) -> v[1] != value[1] @container.find("a.bit-box").each -> $(this).remove() if $(this).data("value")[1] == value[1] @refresh_hidden() + @options.afterRemove(this, value) + @options.afterChange(this, oldValues) + refresh_hidden: -> @hidden.val(@values_real().join(@options.separator)) # Input Observer Helper class $.MultiSelect.InputObserver constructor: (element) -> @input = $(element) @input.keydown (e) => @handle_keydown(e) @events = [] bind: (key, callback) -> @events.push([key, callback]) handle_keydown: (e) -> for event in @events [keys, callback] = event keys = [keys] unless keys.push callback(e) if $.inArray(e.keyCode, keys) > -1 # Selection Helper class $.MultiSelect.Selection constructor: (element) -> @input = $(element)[0] get_caret: -> # For IE if document.selection r = document.selection.createRange().duplicate() r.moveEnd('character', @input.value.length) if r.text == '' [@input.value.length, @input.value.length] else [@input.value.lastIndexOf(r.text), @input.value.lastIndexOf(r.text)] # Others else [@input.selectionStart, @input.selectionEnd] set_caret: (begin, end) -> end ?= begin @input.selectionStart = begin @input.selectionEnd = end set_caret_at_end: -> @set_caret(@input.value.length) # Resizable Input Helper class $.MultiSelect.ResizableInput constructor: (element) -> @input = $(element) @create_measurer() @input.keypress (e) => @set_width(e) @input.keyup (e) => @set_width(e) @input.change (e) => @set_width(e) create_measurer: -> if $("#__jquery_multiselect_measurer")[0] == undefined measurer = $(document.createElement("div")) measurer.attr("id", "__jquery_multiselect_measurer") measurer.css { position: "absolute" left: "-1000px" top: "-1000px" } $(document.body).append(measurer) @measurer = $("#__jquery_multiselect_measurer:first") @measurer.css { fontSize: @input.css('font-size') fontFamily: @input.css('font-family') } calculate_width: -> @measurer.html(@input.val().entitizeHTML() + 'MM') @measurer.innerWidth() set_width: -> @input.css("width", @calculate_width() + "px") # AutoComplete Helper class $.MultiSelect.AutoComplete constructor: (multiselect, completions) -> @multiselect = multiselect @input = @multiselect.input @completions = @parse_completions(completions) @matches = [] @create_elements() @bind_events() parse_completions: (completions) -> $.map completions, (value) -> if typeof value == "string" [[value, value]] else if value instanceof Array and value.length == 2 [value] else if value.value and value.caption [[value.caption, value.value]] else console.error "Invalid option #{value}" if console labelForValue: (value) -> for completion in @completions [label, val] = completion return label if val == value value create_elements: -> @container = $(document.createElement("div")) @container.addClass("jquery-multiselect-autocomplete") @container.css("width", @multiselect.container.outerWidth()) @container.css("display", "none") @container.append(@def) @list = $(document.createElement("ul")) @list.addClass("feed") @container.append(@list) @multiselect.container.after(@container) bind_events: -> @input.keypress (e) => @search(e) @input.keyup (e) => @search(e) @input.change (e) => @search(e) @multiselect.observer.bind KEY.UP, (e) => e.preventDefault(); @navigate_up() @multiselect.observer.bind KEY.DOWN, (e) => e.preventDefault(); @navigate_down() search: -> return if @input.val().trim() == @query # dont do operation if query is same @query = @input.val().trim() @list.html("") # clear list @current = 0 if @query.present() @container.fadeIn("fast") @matches = @matching_completions(@query) if @multiselect.options.enable_new_options def = @create_item("Add <em>" + @query + "</em>") def.mouseover (e) => @select_index(0) for option, i in @matches x = if @multiselect.options.enable_new_options then i + 1 else i item = @create_item(@highlight(option[0], @query)) item.mouseover (e) => @select_index(x) @matches.unshift([@query, @query]) if @multiselect.options.enable_new_options @select_index(0) else @matches = [] @hide_complete_box() @query = null hide_complete_box: -> @container.fadeOut("fast") select_index: (index) -> items = @list.find("li") items.removeClass("auto-focus") items.filter(":eq(#{index})").addClass("auto-focus") @current = index navigate_down: -> next = @current + 1 next = 0 if next >= @matches.length @select_index(next) navigate_up: -> next = @current - 1 next = @matches.length - 1 if next < 0 @select_index(next) create_item: (text, highlight) -> item = $(document.createElement("li")) item.click => @multiselect.add_and_reset() @search() @input.focus() item.html(text) @list.append(item) item val: -> @matches[@current] highlight: (text, highlight) -> if @multiselect.options.complex_search highlighted = "" current = 0 for char, i in text char = text.charAt(i) if current < highlight.length and char.toLowerCase() == highlight.charAt(current).toLowerCase() highlighted += "<em>#{char}</em>" current++ else highlighted += char highlighted else reg = "(#{RegExp.escape(highlight)})" text.replace(new RegExp(reg, "gi"), '<em>$1</em>') matching_completions: (text) -> if @multiselect.options.complex_search reg = "" for char, i in text char = text.charAt(i) reg += RegExp.escape(char) + ".*" reg = new RegExp(reg, "i") else reg = new RegExp(RegExp.escape(text), "i") count = 0 $.grep @completions, (c) => return false if count >= @multiselect.options.max_complete_results return false if $.inArray(c[1], @multiselect.values_real()) > -1 if c[0].match(reg) count++ true else false # Hook jQuery extension $.fn.multiselect = (options) -> options ?= {} $(this).each -> if this.tagName.toLowerCase() == "select" input = $(document.createElement("input")) input.attr("type", "text") input.attr("name", this.name) input.attr("id", this.id) completions = [] add = [] for option in this.options completions.push([option.innerHTML, option.value]) add.push([option.innerHTML, option.value]) if option.selected select_options = { completions: completions enable_new_options: false } $.extend(select_options, options) $(this).replaceWith(input) multiselect = new $.MultiSelect(input, select_options) multiselect.add(val) for val in add multiselect else if this.tagName.toLowerCase() == "input" and this.type == "text" new $.MultiSelect(this, options) $.extend String.prototype, { trim: -> this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, '') entitizeHTML: -> this.replace(/</g,'&lt;').replace(/>/g,'&gt;') unentitizeHTML: -> this.replace(/&lt;/g,'<').replace(/&gt;/g,'>') blank: -> this.trim().length == 0 present: -> not @blank() } RegExp.escape = (str) -> String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1') )(jQuery)
wilkerlucio/jquery-multiselect
f642de41639a9aaeed847baff4422a55f723639b
deploy version 0.1.9
diff --git a/VERSION b/VERSION index 699c6c6..1a03094 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.1.8 +0.1.9 diff --git a/dist/jquery.multiselect.0.1.9.min.js b/dist/jquery.multiselect.0.1.9.min.js new file mode 100644 index 0000000..c3c56f0 --- /dev/null +++ b/dist/jquery.multiselect.0.1.9.min.js @@ -0,0 +1,45 @@ +/** + * Copyright (c) 2010 Wilker Lúcio + * + * 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. + */ + +(function(){var __bind=function(fn,me){return function(){return fn.apply(me,arguments);};};(function($){var KEY;KEY={BACKSPACE:8,TAB:9,RETURN:13,ESCAPE:27,SPACE:32,LEFT:37,UP:38,RIGHT:39,DOWN:40,COLON:188,DOT:190};$.MultiSelect=(function(){function MultiSelect(element,options){this.options={separator:",",completions:[],max_complete_results:5,enable_new_options:true,complex_search:true};$.extend(this.options,options||{});this.values=[];this.input=$(element);this.initialize_elements();this.initialize_events();this.parse_value(0,true);} +MultiSelect.prototype.initialize_elements=function(){this.hidden=$(document.createElement("input"));this.hidden.attr("name",this.input.attr("name"));this.hidden.attr("type","hidden");this.input.removeAttr("name");this.container=$(document.createElement("div"));this.container.addClass("jquery-multiselect");this.input_wrapper=$(document.createElement("a"));this.input_wrapper.addClass("bit-input");this.input.replaceWith(this.container);this.container.append(this.input_wrapper);this.input_wrapper.append(this.input);return this.container.before(this.hidden);};MultiSelect.prototype.initialize_events=function(){this.selection=new $.MultiSelect.Selection(this.input);this.resizable=new $.MultiSelect.ResizableInput(this.input);this.observer=new $.MultiSelect.InputObserver(this.input);this.autocomplete=new $.MultiSelect.AutoComplete(this,this.options.completions);this.input.click(__bind(function(e){return e.stopPropagation();},this));this.input.keyup(__bind(function(){return this.parse_value(1);},this));this.container.click(__bind(function(){this.input.focus();return this.selection.set_caret_at_end();},this));this.observer.bind([KEY.TAB,KEY.RETURN],__bind(function(e){if(this.autocomplete.val()){e.preventDefault();return this.add_and_reset();}},this));this.observer.bind([KEY.BACKSPACE],__bind(function(e){var caret;if(this.values.length<=0){return;} +caret=this.selection.get_caret();if(caret[0]===0&&caret[1]===0){e.preventDefault();return this.remove(this.values[this.values.length-1]);}},this));this.input.blur(__bind(function(){return setTimeout(__bind(function(){return this.autocomplete.hide_complete_box();},this),200);},this));return this.observer.bind([KEY.ESCAPE],__bind(function(e){return this.autocomplete.hide_complete_box();},this));};MultiSelect.prototype.values_real=function(){return $.map(this.values,function(v){return v[1];});};MultiSelect.prototype.parse_value=function(min,checkKey){var label,value,values,_i,_len;if(min==null){min=0;} +if(checkKey==null){checkKey=false;} +values=this.input.val().split(this.options.separator);if(values.length>min){for(_i=0,_len=values.length;_i<_len;_i++){value=values[_i];label=checkKey?this.autocomplete.labelForValue(value):value;if(value.present()){this.add([label,value]);}} +this.input.val("");return this.autocomplete.search();}};MultiSelect.prototype.add_and_reset=function(){if(this.autocomplete.val()){this.add(this.autocomplete.val());this.input.val("");return this.autocomplete.search();}};MultiSelect.prototype.add=function(value){var a,close;if($.inArray(value[1],this.values_real())>-1){return;} +if(value[0].blank()){return;} +value[1]=value[1].trim();this.values.push(value);a=$(document.createElement("a"));a.addClass("bit bit-box");a.mouseover(function(){return $(this).addClass("bit-hover");});a.mouseout(function(){return $(this).removeClass("bit-hover");});a.data("value",value);a.html(value[0].entitizeHTML());close=$(document.createElement("a"));close.addClass("closebutton");close.click(__bind(function(){return this.remove(a.data("value"));},this));a.append(close);this.input_wrapper.before(a);return this.refresh_hidden();};MultiSelect.prototype.remove=function(value){this.values=$.grep(this.values,function(v){return v[1]!==value[1];});this.container.find("a.bit-box").each(function(){if($(this).data("value")[1]===value[1]){return $(this).remove();}});return this.refresh_hidden();};MultiSelect.prototype.refresh_hidden=function(){return this.hidden.val(this.values_real().join(this.options.separator));};return MultiSelect;})();$.MultiSelect.InputObserver=(function(){function InputObserver(element){this.input=$(element);this.input.keydown(__bind(function(e){return this.handle_keydown(e);},this));this.events=[];} +InputObserver.prototype.bind=function(key,callback){return this.events.push([key,callback]);};InputObserver.prototype.handle_keydown=function(e){var callback,event,keys,_i,_len,_ref,_results;_ref=this.events;_results=[];for(_i=0,_len=_ref.length;_i<_len;_i++){event=_ref[_i];keys=event[0],callback=event[1];if(!keys.push){keys=[keys];} +_results.push($.inArray(e.keyCode,keys)>-1?callback(e):void 0);} +return _results;};return InputObserver;})();$.MultiSelect.Selection=(function(){function Selection(element){this.input=$(element)[0];} +Selection.prototype.get_caret=function(){var r;if(document.selection){r=document.selection.createRange().duplicate();r.moveEnd('character',this.input.value.length);if(r.text===''){return[this.input.value.length,this.input.value.length];}else{return[this.input.value.lastIndexOf(r.text),this.input.value.lastIndexOf(r.text)];}}else{return[this.input.selectionStart,this.input.selectionEnd];}};Selection.prototype.set_caret=function(begin,end){end!=null?end:end=begin;this.input.selectionStart=begin;return this.input.selectionEnd=end;};Selection.prototype.set_caret_at_end=function(){return this.set_caret(this.input.value.length);};return Selection;})();$.MultiSelect.ResizableInput=(function(){function ResizableInput(element){this.input=$(element);this.create_measurer();this.input.keypress(__bind(function(e){return this.set_width(e);},this));this.input.keyup(__bind(function(e){return this.set_width(e);},this));this.input.change(__bind(function(e){return this.set_width(e);},this));} +ResizableInput.prototype.create_measurer=function(){var measurer;if($("#__jquery_multiselect_measurer")[0]===void 0){measurer=$(document.createElement("div"));measurer.attr("id","__jquery_multiselect_measurer");measurer.css({position:"absolute",left:"-1000px",top:"-1000px"});$(document.body).append(measurer);} +this.measurer=$("#__jquery_multiselect_measurer:first");return this.measurer.css({fontSize:this.input.css('font-size'),fontFamily:this.input.css('font-family')});};ResizableInput.prototype.calculate_width=function(){this.measurer.html(this.input.val().entitizeHTML()+'MM');return this.measurer.innerWidth();};ResizableInput.prototype.set_width=function(){return this.input.css("width",this.calculate_width()+"px");};return ResizableInput;})();$.MultiSelect.AutoComplete=(function(){function AutoComplete(multiselect,completions){this.multiselect=multiselect;this.input=this.multiselect.input;this.completions=this.parse_completions(completions);this.matches=[];this.create_elements();this.bind_events();} +AutoComplete.prototype.parse_completions=function(completions){return $.map(completions,function(value){if(typeof value==="string"){return[[value,value]];}else if(value instanceof Array&&value.length===2){return[value];}else if(value.value&&value.caption){return[[value.caption,value.value]];}else{if(console){return console.error("Invalid option "+value);}}});};AutoComplete.prototype.labelForValue=function(value){var completion,label,val,_i,_len,_ref;_ref=this.completions;for(_i=0,_len=_ref.length;_i<_len;_i++){completion=_ref[_i];label=completion[0],val=completion[1];if(val===value){return label;}} +return value;};AutoComplete.prototype.create_elements=function(){this.container=$(document.createElement("div"));this.container.addClass("jquery-multiselect-autocomplete");this.container.css("width",this.multiselect.container.outerWidth());this.container.css("display","none");this.container.append(this.def);this.list=$(document.createElement("ul"));this.list.addClass("feed");this.container.append(this.list);return this.multiselect.container.after(this.container);};AutoComplete.prototype.bind_events=function(){this.input.keypress(__bind(function(e){return this.search(e);},this));this.input.keyup(__bind(function(e){return this.search(e);},this));this.input.change(__bind(function(e){return this.search(e);},this));this.multiselect.observer.bind(KEY.UP,__bind(function(e){e.preventDefault();return this.navigate_up();},this));return this.multiselect.observer.bind(KEY.DOWN,__bind(function(e){e.preventDefault();return this.navigate_down();},this));};AutoComplete.prototype.search=function(){var def,i,item,option,x,_len,_ref;if(this.input.val().trim()===this.query){return;} +this.query=this.input.val().trim();this.list.html("");this.current=0;if(this.query.present()){this.container.fadeIn("fast");this.matches=this.matching_completions(this.query);if(this.multiselect.options.enable_new_options){def=this.create_item("Add <em>"+this.query+"</em>");def.mouseover(__bind(function(e){return this.select_index(0);},this));} +_ref=this.matches;for(i=0,_len=_ref.length;i<_len;i++){option=_ref[i];x=this.multiselect.options.enable_new_options?i+1:i;item=this.create_item(this.highlight(option[0],this.query));item.mouseover(__bind(function(e){return this.select_index(x);},this));} +if(this.multiselect.options.enable_new_options){this.matches.unshift([this.query,this.query]);} +return this.select_index(0);}else{this.matches=[];this.hide_complete_box();return this.query=null;}};AutoComplete.prototype.hide_complete_box=function(){return this.container.fadeOut("fast");};AutoComplete.prototype.select_index=function(index){var items;items=this.list.find("li");items.removeClass("auto-focus");items.filter(":eq("+index+")").addClass("auto-focus");return this.current=index;};AutoComplete.prototype.navigate_down=function(){var next;next=this.current+1;if(next>=this.matches.length){next=0;} +return this.select_index(next);};AutoComplete.prototype.navigate_up=function(){var next;next=this.current-1;if(next<0){next=this.matches.length-1;} +return this.select_index(next);};AutoComplete.prototype.create_item=function(text,highlight){var item;item=$(document.createElement("li"));item.click(__bind(function(){this.multiselect.add_and_reset();this.search();return this.input.focus();},this));item.html(text);this.list.append(item);return item;};AutoComplete.prototype.val=function(){return this.matches[this.current];};AutoComplete.prototype.highlight=function(text,highlight){var char,current,highlighted,i,reg,_len;if(this.multiselect.options.complex_search){highlighted="";current=0;for(i=0,_len=text.length;i<_len;i++){char=text[i];char=text.charAt(i);if(current<highlight.length&&char.toLowerCase()===highlight.charAt(current).toLowerCase()){highlighted+="<em>"+char+"</em>";current++;}else{highlighted+=char;}} +return highlighted;}else{reg="("+(RegExp.escape(highlight))+")";return text.replace(new RegExp(reg,"gi"),'<em>$1</em>');}};AutoComplete.prototype.matching_completions=function(text){var char,count,i,reg,_len;if(this.multiselect.options.complex_search){reg="";for(i=0,_len=text.length;i<_len;i++){char=text[i];char=text.charAt(i);reg+=RegExp.escape(char)+".*";} +reg=new RegExp(reg,"i");}else{reg=new RegExp(RegExp.escape(text),"i");} +count=0;return $.grep(this.completions,__bind(function(c){if(count>=this.multiselect.options.max_complete_results){return false;} +if($.inArray(c[1],this.multiselect.values_real())>-1){return false;} +if(c[0].match(reg)){count++;return true;}else{return false;}},this));};return AutoComplete;})();$.fn.multiselect=function(options){options!=null?options:options={};return $(this).each(function(){var add,completions,input,multiselect,option,select_options,val,_i,_j,_len,_len2,_ref;if(this.tagName.toLowerCase()==="select"){input=$(document.createElement("input"));input.attr("type","text");input.attr("name",this.name);input.attr("id",this.id);completions=[];add=[];_ref=this.options;for(_i=0,_len=_ref.length;_i<_len;_i++){option=_ref[_i];completions.push([option.innerHTML,option.value]);if(option.selected){add.push([option.innerHTML,option.value]);}} +select_options={completions:completions,enable_new_options:false};$.extend(select_options,options);$(this).replaceWith(input);multiselect=new $.MultiSelect(input,select_options);for(_j=0,_len2=add.length;_j<_len2;_j++){val=add[_j];multiselect.add(val);} +return multiselect;}else if(this.tagName.toLowerCase()==="input"&&this.type==="text"){return new $.MultiSelect(this,options);}});};$.extend(String.prototype,{trim:function(){return this.replace(/^[\r\n\s]/g,'').replace(/[\r\n\s]$/g,'');},entitizeHTML:function(){return this.replace(/</g,'&lt;').replace(/>/g,'&gt;');},unentitizeHTML:function(){return this.replace(/&lt;/g,'<').replace(/&gt;/g,'>');},blank:function(){return this.trim().length===0;},present:function(){return!this.blank();}});return RegExp.escape=function(str){return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g,'\\$1');};})(jQuery);}).call(this); \ No newline at end of file
wilkerlucio/jquery-multiselect
9f7f56befe9af0daf3dd8313a5f2907a2678d917
automatic add selected options when creating from an select
diff --git a/examples/index.html b/examples/index.html index bb9209d..a83e1d5 100644 --- a/examples/index.html +++ b/examples/index.html @@ -1,48 +1,48 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>JqueryMultiSelect Example</title> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> <link rel="stylesheet" type="text/css" href="../css/jquery.multiselect.css" media="all"> <script type="text/javascript" src="../vendor/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="../js/jquery.multiselect.js"></script> <script type="text/javascript"> names = [ "Alejandra Pizarnik", ["Alicia Partnoy", "alicia"], {caption: "Andres Rivera", value: "andres"}, "Antonio Porchia", "Arturo Andres Roig", "Felipe Pigna", "Gustavo Nielsen", "Hector German Oesterheld", "Juan Carlos Portantiero", "Juan L. Ortiz", "Manuel Mujica Lainez", "Manuel Puig", "Mario Rodriguez Cobos", "Olga Orozco", "Osvaldo Tierra", "Ricardo Piglia", "Ricardo Rojas", "Roberto Payro", "Silvina Ocampo", "Victoria Ocampo", "Zuriel Barron" ] $(function() { $("#sample-tags").multiselect({completions: names}); $("#sample-select").multiselect(); }); </script> </head> <body> <input type="text" name="tags" id="sample-tags" value="initial,values,andres" /> <select multiple="multiple" size="5" id="sample-select" name="sample-select"> - <option value="car">Car</option> + <option value="car" selected="selected">Car</option> <option value="ship">Ship</option> - <option value="bus">Bus</option> + <option value="bus" selected="selected">Bus</option> </select> </body> </html> diff --git a/js/jquery.multiselect.js b/js/jquery.multiselect.js index 0542555..baa374b 100644 --- a/js/jquery.multiselect.js +++ b/js/jquery.multiselect.js @@ -1,506 +1,515 @@ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; (function($) { var KEY; KEY = { BACKSPACE: 8, TAB: 9, RETURN: 13, ESCAPE: 27, SPACE: 32, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, COLON: 188, DOT: 190 }; $.MultiSelect = (function() { function MultiSelect(element, options) { this.options = { separator: ",", completions: [], max_complete_results: 5, enable_new_options: true, complex_search: true }; $.extend(this.options, options || {}); this.values = []; this.input = $(element); this.initialize_elements(); this.initialize_events(); this.parse_value(0, true); } MultiSelect.prototype.initialize_elements = function() { this.hidden = $(document.createElement("input")); this.hidden.attr("name", this.input.attr("name")); this.hidden.attr("type", "hidden"); this.input.removeAttr("name"); this.container = $(document.createElement("div")); this.container.addClass("jquery-multiselect"); this.input_wrapper = $(document.createElement("a")); this.input_wrapper.addClass("bit-input"); this.input.replaceWith(this.container); this.container.append(this.input_wrapper); this.input_wrapper.append(this.input); return this.container.before(this.hidden); }; MultiSelect.prototype.initialize_events = function() { this.selection = new $.MultiSelect.Selection(this.input); this.resizable = new $.MultiSelect.ResizableInput(this.input); this.observer = new $.MultiSelect.InputObserver(this.input); this.autocomplete = new $.MultiSelect.AutoComplete(this, this.options.completions); this.input.click(__bind(function(e) { return e.stopPropagation(); }, this)); this.input.keyup(__bind(function() { return this.parse_value(1); }, this)); this.container.click(__bind(function() { this.input.focus(); return this.selection.set_caret_at_end(); }, this)); this.observer.bind([KEY.TAB, KEY.RETURN], __bind(function(e) { if (this.autocomplete.val()) { e.preventDefault(); return this.add_and_reset(); } }, this)); this.observer.bind([KEY.BACKSPACE], __bind(function(e) { var caret; if (this.values.length <= 0) { return; } caret = this.selection.get_caret(); if (caret[0] === 0 && caret[1] === 0) { e.preventDefault(); return this.remove(this.values[this.values.length - 1]); } }, this)); this.input.blur(__bind(function() { return setTimeout(__bind(function() { return this.autocomplete.hide_complete_box(); }, this), 200); }, this)); return this.observer.bind([KEY.ESCAPE], __bind(function(e) { return this.autocomplete.hide_complete_box(); }, this)); }; MultiSelect.prototype.values_real = function() { return $.map(this.values, function(v) { return v[1]; }); }; MultiSelect.prototype.parse_value = function(min, checkKey) { var label, value, values, _i, _len; if (min == null) { min = 0; } if (checkKey == null) { checkKey = false; } values = this.input.val().split(this.options.separator); if (values.length > min) { for (_i = 0, _len = values.length; _i < _len; _i++) { value = values[_i]; label = checkKey ? this.autocomplete.labelForValue(value) : value; if (value.present()) { this.add([label, value]); } } this.input.val(""); return this.autocomplete.search(); } }; MultiSelect.prototype.add_and_reset = function() { if (this.autocomplete.val()) { this.add(this.autocomplete.val()); this.input.val(""); return this.autocomplete.search(); } }; MultiSelect.prototype.add = function(value) { var a, close; if ($.inArray(value[1], this.values_real()) > -1) { return; } if (value[0].blank()) { return; } value[1] = value[1].trim(); this.values.push(value); a = $(document.createElement("a")); a.addClass("bit bit-box"); a.mouseover(function() { return $(this).addClass("bit-hover"); }); a.mouseout(function() { return $(this).removeClass("bit-hover"); }); a.data("value", value); a.html(value[0].entitizeHTML()); close = $(document.createElement("a")); close.addClass("closebutton"); close.click(__bind(function() { return this.remove(a.data("value")); }, this)); a.append(close); this.input_wrapper.before(a); return this.refresh_hidden(); }; MultiSelect.prototype.remove = function(value) { this.values = $.grep(this.values, function(v) { return v[1] !== value[1]; }); this.container.find("a.bit-box").each(function() { if ($(this).data("value")[1] === value[1]) { return $(this).remove(); } }); return this.refresh_hidden(); }; MultiSelect.prototype.refresh_hidden = function() { return this.hidden.val(this.values_real().join(this.options.separator)); }; return MultiSelect; })(); $.MultiSelect.InputObserver = (function() { function InputObserver(element) { this.input = $(element); this.input.keydown(__bind(function(e) { return this.handle_keydown(e); }, this)); this.events = []; } InputObserver.prototype.bind = function(key, callback) { return this.events.push([key, callback]); }; InputObserver.prototype.handle_keydown = function(e) { var callback, event, keys, _i, _len, _ref, _results; _ref = this.events; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { event = _ref[_i]; keys = event[0], callback = event[1]; if (!keys.push) { keys = [keys]; } _results.push($.inArray(e.keyCode, keys) > -1 ? callback(e) : void 0); } return _results; }; return InputObserver; })(); $.MultiSelect.Selection = (function() { function Selection(element) { this.input = $(element)[0]; } Selection.prototype.get_caret = function() { var r; if (document.selection) { r = document.selection.createRange().duplicate(); r.moveEnd('character', this.input.value.length); if (r.text === '') { return [this.input.value.length, this.input.value.length]; } else { return [this.input.value.lastIndexOf(r.text), this.input.value.lastIndexOf(r.text)]; } } else { return [this.input.selectionStart, this.input.selectionEnd]; } }; Selection.prototype.set_caret = function(begin, end) { end != null ? end : end = begin; this.input.selectionStart = begin; return this.input.selectionEnd = end; }; Selection.prototype.set_caret_at_end = function() { return this.set_caret(this.input.value.length); }; return Selection; })(); $.MultiSelect.ResizableInput = (function() { function ResizableInput(element) { this.input = $(element); this.create_measurer(); this.input.keypress(__bind(function(e) { return this.set_width(e); }, this)); this.input.keyup(__bind(function(e) { return this.set_width(e); }, this)); this.input.change(__bind(function(e) { return this.set_width(e); }, this)); } ResizableInput.prototype.create_measurer = function() { var measurer; if ($("#__jquery_multiselect_measurer")[0] === void 0) { measurer = $(document.createElement("div")); measurer.attr("id", "__jquery_multiselect_measurer"); measurer.css({ position: "absolute", left: "-1000px", top: "-1000px" }); $(document.body).append(measurer); } this.measurer = $("#__jquery_multiselect_measurer:first"); return this.measurer.css({ fontSize: this.input.css('font-size'), fontFamily: this.input.css('font-family') }); }; ResizableInput.prototype.calculate_width = function() { this.measurer.html(this.input.val().entitizeHTML() + 'MM'); return this.measurer.innerWidth(); }; ResizableInput.prototype.set_width = function() { return this.input.css("width", this.calculate_width() + "px"); }; return ResizableInput; })(); $.MultiSelect.AutoComplete = (function() { function AutoComplete(multiselect, completions) { this.multiselect = multiselect; this.input = this.multiselect.input; this.completions = this.parse_completions(completions); this.matches = []; this.create_elements(); this.bind_events(); } AutoComplete.prototype.parse_completions = function(completions) { return $.map(completions, function(value) { if (typeof value === "string") { return [[value, value]]; } else if (value instanceof Array && value.length === 2) { return [value]; } else if (value.value && value.caption) { return [[value.caption, value.value]]; } else { if (console) { return console.error("Invalid option " + value); } } }); }; AutoComplete.prototype.labelForValue = function(value) { var completion, label, val, _i, _len, _ref; _ref = this.completions; for (_i = 0, _len = _ref.length; _i < _len; _i++) { completion = _ref[_i]; label = completion[0], val = completion[1]; if (val === value) { return label; } } return value; }; AutoComplete.prototype.create_elements = function() { this.container = $(document.createElement("div")); this.container.addClass("jquery-multiselect-autocomplete"); this.container.css("width", this.multiselect.container.outerWidth()); this.container.css("display", "none"); this.container.append(this.def); this.list = $(document.createElement("ul")); this.list.addClass("feed"); this.container.append(this.list); return this.multiselect.container.after(this.container); }; AutoComplete.prototype.bind_events = function() { this.input.keypress(__bind(function(e) { return this.search(e); }, this)); this.input.keyup(__bind(function(e) { return this.search(e); }, this)); this.input.change(__bind(function(e) { return this.search(e); }, this)); this.multiselect.observer.bind(KEY.UP, __bind(function(e) { e.preventDefault(); return this.navigate_up(); }, this)); return this.multiselect.observer.bind(KEY.DOWN, __bind(function(e) { e.preventDefault(); return this.navigate_down(); }, this)); }; AutoComplete.prototype.search = function() { var def, i, item, option, x, _len, _ref; if (this.input.val().trim() === this.query) { return; } this.query = this.input.val().trim(); this.list.html(""); this.current = 0; if (this.query.present()) { this.container.fadeIn("fast"); this.matches = this.matching_completions(this.query); if (this.multiselect.options.enable_new_options) { def = this.create_item("Add <em>" + this.query + "</em>"); def.mouseover(__bind(function(e) { return this.select_index(0); }, this)); } _ref = this.matches; for (i = 0, _len = _ref.length; i < _len; i++) { option = _ref[i]; x = this.multiselect.options.enable_new_options ? i + 1 : i; item = this.create_item(this.highlight(option[0], this.query)); item.mouseover(__bind(function(e) { return this.select_index(x); }, this)); } if (this.multiselect.options.enable_new_options) { this.matches.unshift([this.query, this.query]); } return this.select_index(0); } else { this.matches = []; this.hide_complete_box(); return this.query = null; } }; AutoComplete.prototype.hide_complete_box = function() { return this.container.fadeOut("fast"); }; AutoComplete.prototype.select_index = function(index) { var items; items = this.list.find("li"); items.removeClass("auto-focus"); items.filter(":eq(" + index + ")").addClass("auto-focus"); return this.current = index; }; AutoComplete.prototype.navigate_down = function() { var next; next = this.current + 1; if (next >= this.matches.length) { next = 0; } return this.select_index(next); }; AutoComplete.prototype.navigate_up = function() { var next; next = this.current - 1; if (next < 0) { next = this.matches.length - 1; } return this.select_index(next); }; AutoComplete.prototype.create_item = function(text, highlight) { var item; item = $(document.createElement("li")); item.click(__bind(function() { this.multiselect.add_and_reset(); this.search(); return this.input.focus(); }, this)); item.html(text); this.list.append(item); return item; }; AutoComplete.prototype.val = function() { return this.matches[this.current]; }; AutoComplete.prototype.highlight = function(text, highlight) { var char, current, highlighted, i, reg, _len; if (this.multiselect.options.complex_search) { highlighted = ""; current = 0; for (i = 0, _len = text.length; i < _len; i++) { char = text[i]; char = text.charAt(i); if (current < highlight.length && char.toLowerCase() === highlight.charAt(current).toLowerCase()) { highlighted += "<em>" + char + "</em>"; current++; } else { highlighted += char; } } return highlighted; } else { reg = "(" + (RegExp.escape(highlight)) + ")"; return text.replace(new RegExp(reg, "gi"), '<em>$1</em>'); } }; AutoComplete.prototype.matching_completions = function(text) { var char, count, i, reg, _len; if (this.multiselect.options.complex_search) { reg = ""; for (i = 0, _len = text.length; i < _len; i++) { char = text[i]; char = text.charAt(i); reg += RegExp.escape(char) + ".*"; } reg = new RegExp(reg, "i"); } else { reg = new RegExp(RegExp.escape(text), "i"); } count = 0; return $.grep(this.completions, __bind(function(c) { if (count >= this.multiselect.options.max_complete_results) { return false; } if ($.inArray(c[1], this.multiselect.values_real()) > -1) { return false; } if (c[0].match(reg)) { count++; return true; } else { return false; } }, this)); }; return AutoComplete; })(); $.fn.multiselect = function(options) { options != null ? options : options = {}; return $(this).each(function() { - var completions, input, option, select_options, _i, _len, _ref; + var add, completions, input, multiselect, option, select_options, val, _i, _j, _len, _len2, _ref; if (this.tagName.toLowerCase() === "select") { input = $(document.createElement("input")); input.attr("type", "text"); input.attr("name", this.name); input.attr("id", this.id); completions = []; + add = []; _ref = this.options; for (_i = 0, _len = _ref.length; _i < _len; _i++) { option = _ref[_i]; completions.push([option.innerHTML, option.value]); + if (option.selected) { + add.push([option.innerHTML, option.value]); + } } select_options = { completions: completions, enable_new_options: false }; $.extend(select_options, options); $(this).replaceWith(input); - return new $.MultiSelect(input, select_options); + multiselect = new $.MultiSelect(input, select_options); + for (_j = 0, _len2 = add.length; _j < _len2; _j++) { + val = add[_j]; + multiselect.add(val); + } + return multiselect; } else if (this.tagName.toLowerCase() === "input" && this.type === "text") { return new $.MultiSelect(this, options); } }); }; $.extend(String.prototype, { trim: function() { return this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, ''); }, entitizeHTML: function() { return this.replace(/</g, '&lt;').replace(/>/g, '&gt;'); }, unentitizeHTML: function() { return this.replace(/&lt;/g, '<').replace(/&gt;/g, '>'); }, blank: function() { return this.trim().length === 0; }, present: function() { return !this.blank(); } }); return RegExp.escape = function(str) { return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); }; })(jQuery); }).call(this); diff --git a/src/jquery.multiselect.coffee b/src/jquery.multiselect.coffee index b0d0119..a667b2f 100644 --- a/src/jquery.multiselect.coffee +++ b/src/jquery.multiselect.coffee @@ -1,426 +1,431 @@ # Copyright (c) 2010 Wilker Lúcio # # 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. (($) -> KEY = { BACKSPACE: 8 TAB: 9 RETURN: 13 ESCAPE: 27 SPACE: 32 LEFT: 37 UP: 38 RIGHT: 39 DOWN: 40 COLON: 188 DOT: 190 } class $.MultiSelect constructor: (element, options) -> @options = { separator: "," completions: [] max_complete_results: 5 enable_new_options: true complex_search: true } $.extend(@options, options || {}) @values = [] @input = $(element) @initialize_elements() @initialize_events() @parse_value(0, true) initialize_elements: -> # hidden input to hold real value @hidden = $(document.createElement("input")) @hidden.attr("name", @input.attr("name")) @hidden.attr("type", "hidden") @input.removeAttr("name") @container = $(document.createElement("div")) @container.addClass("jquery-multiselect") @input_wrapper = $(document.createElement("a")) @input_wrapper.addClass("bit-input") @input.replaceWith(@container) @container.append(@input_wrapper) @input_wrapper.append(@input) @container.before(@hidden) initialize_events: -> # create helpers @selection = new $.MultiSelect.Selection(@input) @resizable = new $.MultiSelect.ResizableInput(@input) @observer = new $.MultiSelect.InputObserver(@input) @autocomplete = new $.MultiSelect.AutoComplete(this, @options.completions) # prevent container click to put carret at end @input.click (e) => e.stopPropagation() # create element when place separator or paste @input.keyup => @parse_value(1) # focus input and set carret at and @container.click => @input.focus() @selection.set_caret_at_end() # add element on press TAB or RETURN @observer.bind [KEY.TAB, KEY.RETURN], (e) => if @autocomplete.val() e.preventDefault() @add_and_reset() # remove last item @observer.bind [KEY.BACKSPACE], (e) => return if @values.length <= 0 caret = @selection.get_caret() if caret[0] == 0 and caret[1] == 0 e.preventDefault() @remove(@values[@values.length - 1]) # hide complete box @input.blur => setTimeout(=> @autocomplete.hide_complete_box() 200) @observer.bind [KEY.ESCAPE], (e) => @autocomplete.hide_complete_box() values_real: -> $.map @values, (v) -> v[1] parse_value: (min = 0, checkKey = false) -> values = @input.val().split(@options.separator) if values.length > min for value in values label = if checkKey then @autocomplete.labelForValue(value) else value @add [label, value] if value.present() @input.val("") @autocomplete.search() add_and_reset: -> if @autocomplete.val() @add(@autocomplete.val()) @input.val("") @autocomplete.search() # add new element add: (value) -> return if $.inArray(value[1], @values_real()) > -1 return if value[0].blank() value[1] = value[1].trim() @values.push(value) a = $(document.createElement("a")) a.addClass("bit bit-box") a.mouseover -> $(this).addClass("bit-hover") a.mouseout -> $(this).removeClass("bit-hover") a.data("value", value) a.html(value[0].entitizeHTML()) close = $(document.createElement("a")) close.addClass("closebutton") close.click => @remove(a.data("value")) a.append(close) @input_wrapper.before(a) @refresh_hidden() remove: (value) -> @values = $.grep @values, (v) -> v[1] != value[1] @container.find("a.bit-box").each -> $(this).remove() if $(this).data("value")[1] == value[1] @refresh_hidden() refresh_hidden: -> @hidden.val(@values_real().join(@options.separator)) # Input Observer Helper class $.MultiSelect.InputObserver constructor: (element) -> @input = $(element) @input.keydown (e) => @handle_keydown(e) @events = [] bind: (key, callback) -> @events.push([key, callback]) handle_keydown: (e) -> for event in @events [keys, callback] = event keys = [keys] unless keys.push callback(e) if $.inArray(e.keyCode, keys) > -1 # Selection Helper class $.MultiSelect.Selection constructor: (element) -> @input = $(element)[0] get_caret: -> # For IE if document.selection r = document.selection.createRange().duplicate() r.moveEnd('character', @input.value.length) if r.text == '' [@input.value.length, @input.value.length] else [@input.value.lastIndexOf(r.text), @input.value.lastIndexOf(r.text)] # Others else [@input.selectionStart, @input.selectionEnd] set_caret: (begin, end) -> end ?= begin @input.selectionStart = begin @input.selectionEnd = end set_caret_at_end: -> @set_caret(@input.value.length) # Resizable Input Helper class $.MultiSelect.ResizableInput constructor: (element) -> @input = $(element) @create_measurer() @input.keypress (e) => @set_width(e) @input.keyup (e) => @set_width(e) @input.change (e) => @set_width(e) create_measurer: -> if $("#__jquery_multiselect_measurer")[0] == undefined measurer = $(document.createElement("div")) measurer.attr("id", "__jquery_multiselect_measurer") measurer.css { position: "absolute" left: "-1000px" top: "-1000px" } $(document.body).append(measurer) @measurer = $("#__jquery_multiselect_measurer:first") @measurer.css { fontSize: @input.css('font-size') fontFamily: @input.css('font-family') } calculate_width: -> @measurer.html(@input.val().entitizeHTML() + 'MM') @measurer.innerWidth() set_width: -> @input.css("width", @calculate_width() + "px") # AutoComplete Helper class $.MultiSelect.AutoComplete constructor: (multiselect, completions) -> @multiselect = multiselect @input = @multiselect.input @completions = @parse_completions(completions) @matches = [] @create_elements() @bind_events() parse_completions: (completions) -> $.map completions, (value) -> if typeof value == "string" [[value, value]] else if value instanceof Array and value.length == 2 [value] else if value.value and value.caption [[value.caption, value.value]] else console.error "Invalid option #{value}" if console labelForValue: (value) -> for completion in @completions [label, val] = completion return label if val == value value create_elements: -> @container = $(document.createElement("div")) @container.addClass("jquery-multiselect-autocomplete") @container.css("width", @multiselect.container.outerWidth()) @container.css("display", "none") @container.append(@def) @list = $(document.createElement("ul")) @list.addClass("feed") @container.append(@list) @multiselect.container.after(@container) bind_events: -> @input.keypress (e) => @search(e) @input.keyup (e) => @search(e) @input.change (e) => @search(e) @multiselect.observer.bind KEY.UP, (e) => e.preventDefault(); @navigate_up() @multiselect.observer.bind KEY.DOWN, (e) => e.preventDefault(); @navigate_down() search: -> return if @input.val().trim() == @query # dont do operation if query is same @query = @input.val().trim() @list.html("") # clear list @current = 0 if @query.present() @container.fadeIn("fast") @matches = @matching_completions(@query) if @multiselect.options.enable_new_options def = @create_item("Add <em>" + @query + "</em>") def.mouseover (e) => @select_index(0) for option, i in @matches x = if @multiselect.options.enable_new_options then i + 1 else i item = @create_item(@highlight(option[0], @query)) item.mouseover (e) => @select_index(x) @matches.unshift([@query, @query]) if @multiselect.options.enable_new_options @select_index(0) else @matches = [] @hide_complete_box() @query = null hide_complete_box: -> @container.fadeOut("fast") select_index: (index) -> items = @list.find("li") items.removeClass("auto-focus") items.filter(":eq(#{index})").addClass("auto-focus") @current = index navigate_down: -> next = @current + 1 next = 0 if next >= @matches.length @select_index(next) navigate_up: -> next = @current - 1 next = @matches.length - 1 if next < 0 @select_index(next) create_item: (text, highlight) -> item = $(document.createElement("li")) item.click => @multiselect.add_and_reset() @search() @input.focus() item.html(text) @list.append(item) item val: -> @matches[@current] highlight: (text, highlight) -> if @multiselect.options.complex_search highlighted = "" current = 0 for char, i in text char = text.charAt(i) if current < highlight.length and char.toLowerCase() == highlight.charAt(current).toLowerCase() highlighted += "<em>#{char}</em>" current++ else highlighted += char highlighted else reg = "(#{RegExp.escape(highlight)})" text.replace(new RegExp(reg, "gi"), '<em>$1</em>') matching_completions: (text) -> if @multiselect.options.complex_search reg = "" for char, i in text char = text.charAt(i) reg += RegExp.escape(char) + ".*" reg = new RegExp(reg, "i") else reg = new RegExp(RegExp.escape(text), "i") count = 0 $.grep @completions, (c) => return false if count >= @multiselect.options.max_complete_results return false if $.inArray(c[1], @multiselect.values_real()) > -1 if c[0].match(reg) count++ true else false # Hook jQuery extension $.fn.multiselect = (options) -> options ?= {} $(this).each -> if this.tagName.toLowerCase() == "select" input = $(document.createElement("input")) input.attr("type", "text") input.attr("name", this.name) input.attr("id", this.id) completions = [] + add = [] + for option in this.options completions.push([option.innerHTML, option.value]) + add.push([option.innerHTML, option.value]) if option.selected select_options = { completions: completions enable_new_options: false } $.extend(select_options, options) $(this).replaceWith(input) - new $.MultiSelect(input, select_options) + multiselect = new $.MultiSelect(input, select_options) + multiselect.add(val) for val in add + multiselect else if this.tagName.toLowerCase() == "input" and this.type == "text" new $.MultiSelect(this, options) $.extend String.prototype, { trim: -> this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, '') entitizeHTML: -> this.replace(/</g,'&lt;').replace(/>/g,'&gt;') unentitizeHTML: -> this.replace(/&lt;/g,'<').replace(/&gt;/g,'>') blank: -> this.trim().length == 0 present: -> not @blank() } RegExp.escape = (str) -> String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1') )(jQuery)
wilkerlucio/jquery-multiselect
972defc9c4080e3518b768131eb2a895e8188a83
fixed loading initial values, get correct label from completions if it's available
diff --git a/examples/index.html b/examples/index.html index e18bfea..bb9209d 100644 --- a/examples/index.html +++ b/examples/index.html @@ -1,48 +1,48 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>JqueryMultiSelect Example</title> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> <link rel="stylesheet" type="text/css" href="../css/jquery.multiselect.css" media="all"> <script type="text/javascript" src="../vendor/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="../js/jquery.multiselect.js"></script> <script type="text/javascript"> names = [ "Alejandra Pizarnik", ["Alicia Partnoy", "alicia"], {caption: "Andres Rivera", value: "andres"}, "Antonio Porchia", "Arturo Andres Roig", "Felipe Pigna", "Gustavo Nielsen", "Hector German Oesterheld", "Juan Carlos Portantiero", "Juan L. Ortiz", "Manuel Mujica Lainez", "Manuel Puig", "Mario Rodriguez Cobos", "Olga Orozco", "Osvaldo Tierra", "Ricardo Piglia", "Ricardo Rojas", "Roberto Payro", "Silvina Ocampo", "Victoria Ocampo", "Zuriel Barron" ] - + $(function() { $("#sample-tags").multiselect({completions: names}); $("#sample-select").multiselect(); }); </script> </head> <body> - <input type="text" name="tags" id="sample-tags" value="initial,values" /> + <input type="text" name="tags" id="sample-tags" value="initial,values,andres" /> <select multiple="multiple" size="5" id="sample-select" name="sample-select"> <option value="car">Car</option> <option value="ship">Ship</option> <option value="bus">Bus</option> </select> </body> -</html> \ No newline at end of file +</html> diff --git a/js/jquery.multiselect.js b/js/jquery.multiselect.js index 805b2f9..0542555 100644 --- a/js/jquery.multiselect.js +++ b/js/jquery.multiselect.js @@ -1,488 +1,506 @@ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; (function($) { var KEY; KEY = { BACKSPACE: 8, TAB: 9, RETURN: 13, ESCAPE: 27, SPACE: 32, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, COLON: 188, DOT: 190 }; $.MultiSelect = (function() { function MultiSelect(element, options) { this.options = { separator: ",", completions: [], max_complete_results: 5, enable_new_options: true, complex_search: true }; $.extend(this.options, options || {}); this.values = []; this.input = $(element); this.initialize_elements(); this.initialize_events(); - this.parse_value(); + this.parse_value(0, true); } MultiSelect.prototype.initialize_elements = function() { this.hidden = $(document.createElement("input")); this.hidden.attr("name", this.input.attr("name")); this.hidden.attr("type", "hidden"); this.input.removeAttr("name"); this.container = $(document.createElement("div")); this.container.addClass("jquery-multiselect"); this.input_wrapper = $(document.createElement("a")); this.input_wrapper.addClass("bit-input"); this.input.replaceWith(this.container); this.container.append(this.input_wrapper); this.input_wrapper.append(this.input); return this.container.before(this.hidden); }; MultiSelect.prototype.initialize_events = function() { this.selection = new $.MultiSelect.Selection(this.input); this.resizable = new $.MultiSelect.ResizableInput(this.input); this.observer = new $.MultiSelect.InputObserver(this.input); this.autocomplete = new $.MultiSelect.AutoComplete(this, this.options.completions); this.input.click(__bind(function(e) { return e.stopPropagation(); }, this)); this.input.keyup(__bind(function() { return this.parse_value(1); }, this)); this.container.click(__bind(function() { this.input.focus(); return this.selection.set_caret_at_end(); }, this)); this.observer.bind([KEY.TAB, KEY.RETURN], __bind(function(e) { if (this.autocomplete.val()) { e.preventDefault(); return this.add_and_reset(); } }, this)); this.observer.bind([KEY.BACKSPACE], __bind(function(e) { var caret; if (this.values.length <= 0) { return; } caret = this.selection.get_caret(); if (caret[0] === 0 && caret[1] === 0) { e.preventDefault(); return this.remove(this.values[this.values.length - 1]); } }, this)); this.input.blur(__bind(function() { return setTimeout(__bind(function() { return this.autocomplete.hide_complete_box(); }, this), 200); }, this)); return this.observer.bind([KEY.ESCAPE], __bind(function(e) { return this.autocomplete.hide_complete_box(); }, this)); }; MultiSelect.prototype.values_real = function() { return $.map(this.values, function(v) { return v[1]; }); }; - MultiSelect.prototype.parse_value = function(min) { - var value, values, _i, _len; - min != null ? min : min = 0; + MultiSelect.prototype.parse_value = function(min, checkKey) { + var label, value, values, _i, _len; + if (min == null) { + min = 0; + } + if (checkKey == null) { + checkKey = false; + } values = this.input.val().split(this.options.separator); if (values.length > min) { for (_i = 0, _len = values.length; _i < _len; _i++) { value = values[_i]; + label = checkKey ? this.autocomplete.labelForValue(value) : value; if (value.present()) { - this.add([value, value]); + this.add([label, value]); } } this.input.val(""); return this.autocomplete.search(); } }; MultiSelect.prototype.add_and_reset = function() { if (this.autocomplete.val()) { this.add(this.autocomplete.val()); this.input.val(""); return this.autocomplete.search(); } }; MultiSelect.prototype.add = function(value) { var a, close; if ($.inArray(value[1], this.values_real()) > -1) { return; } if (value[0].blank()) { return; } value[1] = value[1].trim(); this.values.push(value); a = $(document.createElement("a")); a.addClass("bit bit-box"); a.mouseover(function() { return $(this).addClass("bit-hover"); }); a.mouseout(function() { return $(this).removeClass("bit-hover"); }); a.data("value", value); a.html(value[0].entitizeHTML()); close = $(document.createElement("a")); close.addClass("closebutton"); close.click(__bind(function() { return this.remove(a.data("value")); }, this)); a.append(close); this.input_wrapper.before(a); return this.refresh_hidden(); }; MultiSelect.prototype.remove = function(value) { this.values = $.grep(this.values, function(v) { return v[1] !== value[1]; }); this.container.find("a.bit-box").each(function() { if ($(this).data("value")[1] === value[1]) { return $(this).remove(); } }); return this.refresh_hidden(); }; MultiSelect.prototype.refresh_hidden = function() { return this.hidden.val(this.values_real().join(this.options.separator)); }; return MultiSelect; })(); $.MultiSelect.InputObserver = (function() { function InputObserver(element) { this.input = $(element); this.input.keydown(__bind(function(e) { return this.handle_keydown(e); }, this)); this.events = []; } InputObserver.prototype.bind = function(key, callback) { return this.events.push([key, callback]); }; InputObserver.prototype.handle_keydown = function(e) { var callback, event, keys, _i, _len, _ref, _results; _ref = this.events; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { event = _ref[_i]; keys = event[0], callback = event[1]; if (!keys.push) { keys = [keys]; } _results.push($.inArray(e.keyCode, keys) > -1 ? callback(e) : void 0); } return _results; }; return InputObserver; })(); $.MultiSelect.Selection = (function() { function Selection(element) { this.input = $(element)[0]; } Selection.prototype.get_caret = function() { var r; if (document.selection) { r = document.selection.createRange().duplicate(); r.moveEnd('character', this.input.value.length); if (r.text === '') { return [this.input.value.length, this.input.value.length]; } else { return [this.input.value.lastIndexOf(r.text), this.input.value.lastIndexOf(r.text)]; } } else { return [this.input.selectionStart, this.input.selectionEnd]; } }; Selection.prototype.set_caret = function(begin, end) { end != null ? end : end = begin; this.input.selectionStart = begin; return this.input.selectionEnd = end; }; Selection.prototype.set_caret_at_end = function() { return this.set_caret(this.input.value.length); }; return Selection; })(); $.MultiSelect.ResizableInput = (function() { function ResizableInput(element) { this.input = $(element); this.create_measurer(); this.input.keypress(__bind(function(e) { return this.set_width(e); }, this)); this.input.keyup(__bind(function(e) { return this.set_width(e); }, this)); this.input.change(__bind(function(e) { return this.set_width(e); }, this)); } ResizableInput.prototype.create_measurer = function() { var measurer; if ($("#__jquery_multiselect_measurer")[0] === void 0) { measurer = $(document.createElement("div")); measurer.attr("id", "__jquery_multiselect_measurer"); measurer.css({ position: "absolute", left: "-1000px", top: "-1000px" }); $(document.body).append(measurer); } this.measurer = $("#__jquery_multiselect_measurer:first"); return this.measurer.css({ fontSize: this.input.css('font-size'), fontFamily: this.input.css('font-family') }); }; ResizableInput.prototype.calculate_width = function() { this.measurer.html(this.input.val().entitizeHTML() + 'MM'); return this.measurer.innerWidth(); }; ResizableInput.prototype.set_width = function() { return this.input.css("width", this.calculate_width() + "px"); }; return ResizableInput; })(); $.MultiSelect.AutoComplete = (function() { function AutoComplete(multiselect, completions) { this.multiselect = multiselect; this.input = this.multiselect.input; this.completions = this.parse_completions(completions); this.matches = []; this.create_elements(); this.bind_events(); } AutoComplete.prototype.parse_completions = function(completions) { return $.map(completions, function(value) { if (typeof value === "string") { return [[value, value]]; } else if (value instanceof Array && value.length === 2) { return [value]; } else if (value.value && value.caption) { return [[value.caption, value.value]]; } else { if (console) { return console.error("Invalid option " + value); } } }); }; + AutoComplete.prototype.labelForValue = function(value) { + var completion, label, val, _i, _len, _ref; + _ref = this.completions; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + completion = _ref[_i]; + label = completion[0], val = completion[1]; + if (val === value) { + return label; + } + } + return value; + }; AutoComplete.prototype.create_elements = function() { this.container = $(document.createElement("div")); this.container.addClass("jquery-multiselect-autocomplete"); this.container.css("width", this.multiselect.container.outerWidth()); this.container.css("display", "none"); this.container.append(this.def); this.list = $(document.createElement("ul")); this.list.addClass("feed"); this.container.append(this.list); return this.multiselect.container.after(this.container); }; AutoComplete.prototype.bind_events = function() { this.input.keypress(__bind(function(e) { return this.search(e); }, this)); this.input.keyup(__bind(function(e) { return this.search(e); }, this)); this.input.change(__bind(function(e) { return this.search(e); }, this)); this.multiselect.observer.bind(KEY.UP, __bind(function(e) { e.preventDefault(); return this.navigate_up(); }, this)); return this.multiselect.observer.bind(KEY.DOWN, __bind(function(e) { e.preventDefault(); return this.navigate_down(); }, this)); }; AutoComplete.prototype.search = function() { var def, i, item, option, x, _len, _ref; if (this.input.val().trim() === this.query) { return; } this.query = this.input.val().trim(); this.list.html(""); this.current = 0; if (this.query.present()) { this.container.fadeIn("fast"); this.matches = this.matching_completions(this.query); if (this.multiselect.options.enable_new_options) { def = this.create_item("Add <em>" + this.query + "</em>"); def.mouseover(__bind(function(e) { return this.select_index(0); }, this)); } _ref = this.matches; for (i = 0, _len = _ref.length; i < _len; i++) { option = _ref[i]; x = this.multiselect.options.enable_new_options ? i + 1 : i; item = this.create_item(this.highlight(option[0], this.query)); item.mouseover(__bind(function(e) { return this.select_index(x); }, this)); } if (this.multiselect.options.enable_new_options) { this.matches.unshift([this.query, this.query]); } return this.select_index(0); } else { this.matches = []; this.hide_complete_box(); return this.query = null; } }; AutoComplete.prototype.hide_complete_box = function() { return this.container.fadeOut("fast"); }; AutoComplete.prototype.select_index = function(index) { var items; items = this.list.find("li"); items.removeClass("auto-focus"); items.filter(":eq(" + index + ")").addClass("auto-focus"); return this.current = index; }; AutoComplete.prototype.navigate_down = function() { var next; next = this.current + 1; if (next >= this.matches.length) { next = 0; } return this.select_index(next); }; AutoComplete.prototype.navigate_up = function() { var next; next = this.current - 1; if (next < 0) { next = this.matches.length - 1; } return this.select_index(next); }; AutoComplete.prototype.create_item = function(text, highlight) { var item; item = $(document.createElement("li")); item.click(__bind(function() { this.multiselect.add_and_reset(); this.search(); return this.input.focus(); }, this)); item.html(text); this.list.append(item); return item; }; AutoComplete.prototype.val = function() { return this.matches[this.current]; }; AutoComplete.prototype.highlight = function(text, highlight) { var char, current, highlighted, i, reg, _len; if (this.multiselect.options.complex_search) { highlighted = ""; current = 0; for (i = 0, _len = text.length; i < _len; i++) { char = text[i]; char = text.charAt(i); if (current < highlight.length && char.toLowerCase() === highlight.charAt(current).toLowerCase()) { highlighted += "<em>" + char + "</em>"; current++; } else { highlighted += char; } } return highlighted; } else { reg = "(" + (RegExp.escape(highlight)) + ")"; return text.replace(new RegExp(reg, "gi"), '<em>$1</em>'); } }; AutoComplete.prototype.matching_completions = function(text) { var char, count, i, reg, _len; if (this.multiselect.options.complex_search) { reg = ""; for (i = 0, _len = text.length; i < _len; i++) { char = text[i]; char = text.charAt(i); reg += RegExp.escape(char) + ".*"; } reg = new RegExp(reg, "i"); } else { reg = new RegExp(RegExp.escape(text), "i"); } count = 0; return $.grep(this.completions, __bind(function(c) { if (count >= this.multiselect.options.max_complete_results) { return false; } if ($.inArray(c[1], this.multiselect.values_real()) > -1) { return false; } if (c[0].match(reg)) { count++; return true; } else { return false; } }, this)); }; return AutoComplete; })(); $.fn.multiselect = function(options) { options != null ? options : options = {}; return $(this).each(function() { var completions, input, option, select_options, _i, _len, _ref; if (this.tagName.toLowerCase() === "select") { input = $(document.createElement("input")); input.attr("type", "text"); input.attr("name", this.name); input.attr("id", this.id); completions = []; _ref = this.options; for (_i = 0, _len = _ref.length; _i < _len; _i++) { option = _ref[_i]; completions.push([option.innerHTML, option.value]); } select_options = { completions: completions, enable_new_options: false }; $.extend(select_options, options); $(this).replaceWith(input); return new $.MultiSelect(input, select_options); } else if (this.tagName.toLowerCase() === "input" && this.type === "text") { return new $.MultiSelect(this, options); } }); }; $.extend(String.prototype, { trim: function() { return this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, ''); }, entitizeHTML: function() { return this.replace(/</g, '&lt;').replace(/>/g, '&gt;'); }, unentitizeHTML: function() { return this.replace(/&lt;/g, '<').replace(/&gt;/g, '>'); }, blank: function() { return this.trim().length === 0; }, present: function() { return !this.blank(); } }); return RegExp.escape = function(str) { return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); }; })(jQuery); }).call(this); diff --git a/src/jquery.multiselect.coffee b/src/jquery.multiselect.coffee index be606fb..b0d0119 100644 --- a/src/jquery.multiselect.coffee +++ b/src/jquery.multiselect.coffee @@ -1,418 +1,426 @@ # Copyright (c) 2010 Wilker Lúcio # # 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. (($) -> KEY = { BACKSPACE: 8 TAB: 9 RETURN: 13 ESCAPE: 27 SPACE: 32 LEFT: 37 UP: 38 RIGHT: 39 DOWN: 40 COLON: 188 DOT: 190 } class $.MultiSelect constructor: (element, options) -> @options = { separator: "," completions: [] max_complete_results: 5 enable_new_options: true complex_search: true } $.extend(@options, options || {}) @values = [] @input = $(element) @initialize_elements() @initialize_events() - @parse_value() + @parse_value(0, true) initialize_elements: -> # hidden input to hold real value @hidden = $(document.createElement("input")) @hidden.attr("name", @input.attr("name")) @hidden.attr("type", "hidden") @input.removeAttr("name") @container = $(document.createElement("div")) @container.addClass("jquery-multiselect") @input_wrapper = $(document.createElement("a")) @input_wrapper.addClass("bit-input") @input.replaceWith(@container) @container.append(@input_wrapper) @input_wrapper.append(@input) @container.before(@hidden) initialize_events: -> # create helpers @selection = new $.MultiSelect.Selection(@input) @resizable = new $.MultiSelect.ResizableInput(@input) @observer = new $.MultiSelect.InputObserver(@input) @autocomplete = new $.MultiSelect.AutoComplete(this, @options.completions) # prevent container click to put carret at end @input.click (e) => e.stopPropagation() # create element when place separator or paste @input.keyup => @parse_value(1) # focus input and set carret at and @container.click => @input.focus() @selection.set_caret_at_end() # add element on press TAB or RETURN @observer.bind [KEY.TAB, KEY.RETURN], (e) => if @autocomplete.val() e.preventDefault() @add_and_reset() # remove last item @observer.bind [KEY.BACKSPACE], (e) => return if @values.length <= 0 caret = @selection.get_caret() if caret[0] == 0 and caret[1] == 0 e.preventDefault() @remove(@values[@values.length - 1]) # hide complete box @input.blur => setTimeout(=> @autocomplete.hide_complete_box() 200) @observer.bind [KEY.ESCAPE], (e) => @autocomplete.hide_complete_box() values_real: -> $.map @values, (v) -> v[1] - parse_value: (min) -> - min ?= 0 + parse_value: (min = 0, checkKey = false) -> values = @input.val().split(@options.separator) if values.length > min for value in values - @add [value, value] if value.present() + label = if checkKey then @autocomplete.labelForValue(value) else value + @add [label, value] if value.present() @input.val("") @autocomplete.search() add_and_reset: -> if @autocomplete.val() @add(@autocomplete.val()) @input.val("") @autocomplete.search() # add new element add: (value) -> return if $.inArray(value[1], @values_real()) > -1 return if value[0].blank() value[1] = value[1].trim() @values.push(value) a = $(document.createElement("a")) a.addClass("bit bit-box") a.mouseover -> $(this).addClass("bit-hover") a.mouseout -> $(this).removeClass("bit-hover") a.data("value", value) a.html(value[0].entitizeHTML()) close = $(document.createElement("a")) close.addClass("closebutton") close.click => @remove(a.data("value")) a.append(close) @input_wrapper.before(a) @refresh_hidden() remove: (value) -> @values = $.grep @values, (v) -> v[1] != value[1] @container.find("a.bit-box").each -> $(this).remove() if $(this).data("value")[1] == value[1] @refresh_hidden() refresh_hidden: -> @hidden.val(@values_real().join(@options.separator)) # Input Observer Helper class $.MultiSelect.InputObserver constructor: (element) -> @input = $(element) @input.keydown (e) => @handle_keydown(e) @events = [] bind: (key, callback) -> @events.push([key, callback]) handle_keydown: (e) -> for event in @events [keys, callback] = event keys = [keys] unless keys.push callback(e) if $.inArray(e.keyCode, keys) > -1 # Selection Helper class $.MultiSelect.Selection constructor: (element) -> @input = $(element)[0] get_caret: -> # For IE if document.selection r = document.selection.createRange().duplicate() r.moveEnd('character', @input.value.length) if r.text == '' [@input.value.length, @input.value.length] else [@input.value.lastIndexOf(r.text), @input.value.lastIndexOf(r.text)] # Others else [@input.selectionStart, @input.selectionEnd] set_caret: (begin, end) -> end ?= begin @input.selectionStart = begin @input.selectionEnd = end set_caret_at_end: -> @set_caret(@input.value.length) # Resizable Input Helper class $.MultiSelect.ResizableInput constructor: (element) -> @input = $(element) @create_measurer() @input.keypress (e) => @set_width(e) @input.keyup (e) => @set_width(e) @input.change (e) => @set_width(e) create_measurer: -> if $("#__jquery_multiselect_measurer")[0] == undefined measurer = $(document.createElement("div")) measurer.attr("id", "__jquery_multiselect_measurer") measurer.css { position: "absolute" left: "-1000px" top: "-1000px" } $(document.body).append(measurer) @measurer = $("#__jquery_multiselect_measurer:first") @measurer.css { fontSize: @input.css('font-size') fontFamily: @input.css('font-family') } calculate_width: -> @measurer.html(@input.val().entitizeHTML() + 'MM') @measurer.innerWidth() set_width: -> @input.css("width", @calculate_width() + "px") # AutoComplete Helper class $.MultiSelect.AutoComplete constructor: (multiselect, completions) -> @multiselect = multiselect @input = @multiselect.input @completions = @parse_completions(completions) @matches = [] @create_elements() @bind_events() parse_completions: (completions) -> $.map completions, (value) -> if typeof value == "string" [[value, value]] else if value instanceof Array and value.length == 2 [value] else if value.value and value.caption [[value.caption, value.value]] else console.error "Invalid option #{value}" if console + labelForValue: (value) -> + for completion in @completions + [label, val] = completion + + return label if val == value + + value + create_elements: -> @container = $(document.createElement("div")) @container.addClass("jquery-multiselect-autocomplete") @container.css("width", @multiselect.container.outerWidth()) @container.css("display", "none") @container.append(@def) @list = $(document.createElement("ul")) @list.addClass("feed") @container.append(@list) @multiselect.container.after(@container) bind_events: -> @input.keypress (e) => @search(e) @input.keyup (e) => @search(e) @input.change (e) => @search(e) @multiselect.observer.bind KEY.UP, (e) => e.preventDefault(); @navigate_up() @multiselect.observer.bind KEY.DOWN, (e) => e.preventDefault(); @navigate_down() search: -> return if @input.val().trim() == @query # dont do operation if query is same @query = @input.val().trim() @list.html("") # clear list @current = 0 if @query.present() @container.fadeIn("fast") @matches = @matching_completions(@query) if @multiselect.options.enable_new_options def = @create_item("Add <em>" + @query + "</em>") def.mouseover (e) => @select_index(0) for option, i in @matches x = if @multiselect.options.enable_new_options then i + 1 else i item = @create_item(@highlight(option[0], @query)) item.mouseover (e) => @select_index(x) @matches.unshift([@query, @query]) if @multiselect.options.enable_new_options @select_index(0) else @matches = [] @hide_complete_box() @query = null hide_complete_box: -> @container.fadeOut("fast") select_index: (index) -> items = @list.find("li") items.removeClass("auto-focus") items.filter(":eq(#{index})").addClass("auto-focus") @current = index navigate_down: -> next = @current + 1 next = 0 if next >= @matches.length @select_index(next) navigate_up: -> next = @current - 1 next = @matches.length - 1 if next < 0 @select_index(next) create_item: (text, highlight) -> item = $(document.createElement("li")) item.click => @multiselect.add_and_reset() @search() @input.focus() item.html(text) @list.append(item) item val: -> @matches[@current] highlight: (text, highlight) -> if @multiselect.options.complex_search highlighted = "" current = 0 for char, i in text char = text.charAt(i) if current < highlight.length and char.toLowerCase() == highlight.charAt(current).toLowerCase() highlighted += "<em>#{char}</em>" current++ else highlighted += char highlighted else reg = "(#{RegExp.escape(highlight)})" text.replace(new RegExp(reg, "gi"), '<em>$1</em>') matching_completions: (text) -> if @multiselect.options.complex_search reg = "" for char, i in text char = text.charAt(i) reg += RegExp.escape(char) + ".*" reg = new RegExp(reg, "i") else reg = new RegExp(RegExp.escape(text), "i") count = 0 $.grep @completions, (c) => return false if count >= @multiselect.options.max_complete_results return false if $.inArray(c[1], @multiselect.values_real()) > -1 if c[0].match(reg) count++ true else false # Hook jQuery extension $.fn.multiselect = (options) -> options ?= {} $(this).each -> if this.tagName.toLowerCase() == "select" input = $(document.createElement("input")) input.attr("type", "text") input.attr("name", this.name) input.attr("id", this.id) completions = [] for option in this.options completions.push([option.innerHTML, option.value]) select_options = { completions: completions enable_new_options: false } $.extend(select_options, options) $(this).replaceWith(input) new $.MultiSelect(input, select_options) else if this.tagName.toLowerCase() == "input" and this.type == "text" new $.MultiSelect(this, options) $.extend String.prototype, { trim: -> this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, '') entitizeHTML: -> this.replace(/</g,'&lt;').replace(/>/g,'&gt;') unentitizeHTML: -> this.replace(/&lt;/g,'<').replace(/&gt;/g,'>') blank: -> this.trim().length == 0 present: -> not @blank() } RegExp.escape = (str) -> String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1') )(jQuery)
wilkerlucio/jquery-multiselect
3c5174928289edf85451de9da483eb220f8b122e
fixed string extension and generated new version
diff --git a/Rakefile b/Rakefile index e962539..68fc3fa 100644 --- a/Rakefile +++ b/Rakefile @@ -1,45 +1,45 @@ # encoding: utf-8 require 'rubygems' require 'bundler' Bundler.setup Bundler.require desc "Compile CoffeeScripts and watch for changes" task :coffee do - coffee = IO.popen 'coffee -wc --no-wrap -o js src/*.coffee 2>&1' + coffee = IO.popen 'coffee -wc -o js src/*.coffee 2>&1' while line = coffee.gets puts line end end desc "Build minified version" task :build do content = File.read("js/jquery.multiselect.js") minyfied = JSMin.minify(content) - version = File.read("VERSION") + version = File.read("VERSION").strip licence = <<LIC /** * Copyright (c) 2010 Wilker Lúcio * * 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. */ LIC File.open("dist/jquery.multiselect.#{version}.min.js", "wb") do |f| f << licence f << minyfied end end diff --git a/VERSION b/VERSION index a1e1395..699c6c6 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.1.7 \ No newline at end of file +0.1.8 diff --git a/dist/jquery.multiselect.0.1.8.min.js b/dist/jquery.multiselect.0.1.8.min.js new file mode 100644 index 0000000..a4ea1e8 --- /dev/null +++ b/dist/jquery.multiselect.0.1.8.min.js @@ -0,0 +1,41 @@ +/** + * Copyright (c) 2010 Wilker Lúcio + * + * 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. + */ + +(function(){var __bind=function(fn,me){return function(){return fn.apply(me,arguments);};};(function($){var KEY;KEY={BACKSPACE:8,TAB:9,RETURN:13,ESCAPE:27,SPACE:32,LEFT:37,UP:38,RIGHT:39,DOWN:40,COLON:188,DOT:190};$.MultiSelect=(function(){function MultiSelect(element,options){this.options={separator:",",completions:[],max_complete_results:5,enable_new_options:true,complex_search:true};$.extend(this.options,options||{});this.values=[];this.input=$(element);this.initialize_elements();this.initialize_events();this.parse_value();} +MultiSelect.prototype.initialize_elements=function(){this.hidden=$(document.createElement("input"));this.hidden.attr("name",this.input.attr("name"));this.hidden.attr("type","hidden");this.input.removeAttr("name");this.container=$(document.createElement("div"));this.container.addClass("jquery-multiselect");this.input_wrapper=$(document.createElement("a"));this.input_wrapper.addClass("bit-input");this.input.replaceWith(this.container);this.container.append(this.input_wrapper);this.input_wrapper.append(this.input);return this.container.before(this.hidden);};MultiSelect.prototype.initialize_events=function(){this.selection=new $.MultiSelect.Selection(this.input);this.resizable=new $.MultiSelect.ResizableInput(this.input);this.observer=new $.MultiSelect.InputObserver(this.input);this.autocomplete=new $.MultiSelect.AutoComplete(this,this.options.completions);this.input.click(__bind(function(e){return e.stopPropagation();},this));this.input.keyup(__bind(function(){return this.parse_value(1);},this));this.container.click(__bind(function(){this.input.focus();return this.selection.set_caret_at_end();},this));this.observer.bind([KEY.TAB,KEY.RETURN],__bind(function(e){if(this.autocomplete.val()){e.preventDefault();return this.add_and_reset();}},this));this.observer.bind([KEY.BACKSPACE],__bind(function(e){var caret;if(this.values.length<=0){return;} +caret=this.selection.get_caret();if(caret[0]===0&&caret[1]===0){e.preventDefault();return this.remove(this.values[this.values.length-1]);}},this));this.input.blur(__bind(function(){return setTimeout(__bind(function(){return this.autocomplete.hide_complete_box();},this),200);},this));return this.observer.bind([KEY.ESCAPE],__bind(function(e){return this.autocomplete.hide_complete_box();},this));};MultiSelect.prototype.values_real=function(){return $.map(this.values,function(v){return v[1];});};MultiSelect.prototype.parse_value=function(min){var value,values,_i,_len;min!=null?min:min=0;values=this.input.val().split(this.options.separator);if(values.length>min){for(_i=0,_len=values.length;_i<_len;_i++){value=values[_i];if(value.present()){this.add([value,value]);}} +this.input.val("");return this.autocomplete.search();}};MultiSelect.prototype.add_and_reset=function(){if(this.autocomplete.val()){this.add(this.autocomplete.val());this.input.val("");return this.autocomplete.search();}};MultiSelect.prototype.add=function(value){var a,close;if($.inArray(value[1],this.values_real())>-1){return;} +if(value[0].blank()){return;} +value[1]=value[1].trim();this.values.push(value);a=$(document.createElement("a"));a.addClass("bit bit-box");a.mouseover(function(){return $(this).addClass("bit-hover");});a.mouseout(function(){return $(this).removeClass("bit-hover");});a.data("value",value);a.html(value[0].entitizeHTML());close=$(document.createElement("a"));close.addClass("closebutton");close.click(__bind(function(){return this.remove(a.data("value"));},this));a.append(close);this.input_wrapper.before(a);return this.refresh_hidden();};MultiSelect.prototype.remove=function(value){this.values=$.grep(this.values,function(v){return v[1]!==value[1];});this.container.find("a.bit-box").each(function(){if($(this).data("value")[1]===value[1]){return $(this).remove();}});return this.refresh_hidden();};MultiSelect.prototype.refresh_hidden=function(){return this.hidden.val(this.values_real().join(this.options.separator));};return MultiSelect;})();$.MultiSelect.InputObserver=(function(){function InputObserver(element){this.input=$(element);this.input.keydown(__bind(function(e){return this.handle_keydown(e);},this));this.events=[];} +InputObserver.prototype.bind=function(key,callback){return this.events.push([key,callback]);};InputObserver.prototype.handle_keydown=function(e){var callback,event,keys,_i,_len,_ref,_results;_ref=this.events;_results=[];for(_i=0,_len=_ref.length;_i<_len;_i++){event=_ref[_i];keys=event[0],callback=event[1];if(!keys.push){keys=[keys];} +_results.push($.inArray(e.keyCode,keys)>-1?callback(e):void 0);} +return _results;};return InputObserver;})();$.MultiSelect.Selection=(function(){function Selection(element){this.input=$(element)[0];} +Selection.prototype.get_caret=function(){var r;if(document.selection){r=document.selection.createRange().duplicate();r.moveEnd('character',this.input.value.length);if(r.text===''){return[this.input.value.length,this.input.value.length];}else{return[this.input.value.lastIndexOf(r.text),this.input.value.lastIndexOf(r.text)];}}else{return[this.input.selectionStart,this.input.selectionEnd];}};Selection.prototype.set_caret=function(begin,end){end!=null?end:end=begin;this.input.selectionStart=begin;return this.input.selectionEnd=end;};Selection.prototype.set_caret_at_end=function(){return this.set_caret(this.input.value.length);};return Selection;})();$.MultiSelect.ResizableInput=(function(){function ResizableInput(element){this.input=$(element);this.create_measurer();this.input.keypress(__bind(function(e){return this.set_width(e);},this));this.input.keyup(__bind(function(e){return this.set_width(e);},this));this.input.change(__bind(function(e){return this.set_width(e);},this));} +ResizableInput.prototype.create_measurer=function(){var measurer;if($("#__jquery_multiselect_measurer")[0]===void 0){measurer=$(document.createElement("div"));measurer.attr("id","__jquery_multiselect_measurer");measurer.css({position:"absolute",left:"-1000px",top:"-1000px"});$(document.body).append(measurer);} +this.measurer=$("#__jquery_multiselect_measurer:first");return this.measurer.css({fontSize:this.input.css('font-size'),fontFamily:this.input.css('font-family')});};ResizableInput.prototype.calculate_width=function(){this.measurer.html(this.input.val().entitizeHTML()+'MM');return this.measurer.innerWidth();};ResizableInput.prototype.set_width=function(){return this.input.css("width",this.calculate_width()+"px");};return ResizableInput;})();$.MultiSelect.AutoComplete=(function(){function AutoComplete(multiselect,completions){this.multiselect=multiselect;this.input=this.multiselect.input;this.completions=this.parse_completions(completions);this.matches=[];this.create_elements();this.bind_events();} +AutoComplete.prototype.parse_completions=function(completions){return $.map(completions,function(value){if(typeof value==="string"){return[[value,value]];}else if(value instanceof Array&&value.length===2){return[value];}else if(value.value&&value.caption){return[[value.caption,value.value]];}else{if(console){return console.error("Invalid option "+value);}}});};AutoComplete.prototype.create_elements=function(){this.container=$(document.createElement("div"));this.container.addClass("jquery-multiselect-autocomplete");this.container.css("width",this.multiselect.container.outerWidth());this.container.css("display","none");this.container.append(this.def);this.list=$(document.createElement("ul"));this.list.addClass("feed");this.container.append(this.list);return this.multiselect.container.after(this.container);};AutoComplete.prototype.bind_events=function(){this.input.keypress(__bind(function(e){return this.search(e);},this));this.input.keyup(__bind(function(e){return this.search(e);},this));this.input.change(__bind(function(e){return this.search(e);},this));this.multiselect.observer.bind(KEY.UP,__bind(function(e){e.preventDefault();return this.navigate_up();},this));return this.multiselect.observer.bind(KEY.DOWN,__bind(function(e){e.preventDefault();return this.navigate_down();},this));};AutoComplete.prototype.search=function(){var def,i,item,option,x,_len,_ref;if(this.input.val().trim()===this.query){return;} +this.query=this.input.val().trim();this.list.html("");this.current=0;if(this.query.present()){this.container.fadeIn("fast");this.matches=this.matching_completions(this.query);if(this.multiselect.options.enable_new_options){def=this.create_item("Add <em>"+this.query+"</em>");def.mouseover(__bind(function(e){return this.select_index(0);},this));} +_ref=this.matches;for(i=0,_len=_ref.length;i<_len;i++){option=_ref[i];x=this.multiselect.options.enable_new_options?i+1:i;item=this.create_item(this.highlight(option[0],this.query));item.mouseover(__bind(function(e){return this.select_index(x);},this));} +if(this.multiselect.options.enable_new_options){this.matches.unshift([this.query,this.query]);} +return this.select_index(0);}else{this.matches=[];this.hide_complete_box();return this.query=null;}};AutoComplete.prototype.hide_complete_box=function(){return this.container.fadeOut("fast");};AutoComplete.prototype.select_index=function(index){var items;items=this.list.find("li");items.removeClass("auto-focus");items.filter(":eq("+index+")").addClass("auto-focus");return this.current=index;};AutoComplete.prototype.navigate_down=function(){var next;next=this.current+1;if(next>=this.matches.length){next=0;} +return this.select_index(next);};AutoComplete.prototype.navigate_up=function(){var next;next=this.current-1;if(next<0){next=this.matches.length-1;} +return this.select_index(next);};AutoComplete.prototype.create_item=function(text,highlight){var item;item=$(document.createElement("li"));item.click(__bind(function(){this.multiselect.add_and_reset();this.search();return this.input.focus();},this));item.html(text);this.list.append(item);return item;};AutoComplete.prototype.val=function(){return this.matches[this.current];};AutoComplete.prototype.highlight=function(text,highlight){var char,current,highlighted,i,reg,_len;if(this.multiselect.options.complex_search){highlighted="";current=0;for(i=0,_len=text.length;i<_len;i++){char=text[i];char=text.charAt(i);if(current<highlight.length&&char.toLowerCase()===highlight.charAt(current).toLowerCase()){highlighted+="<em>"+char+"</em>";current++;}else{highlighted+=char;}} +return highlighted;}else{reg="("+(RegExp.escape(highlight))+")";return text.replace(new RegExp(reg,"gi"),'<em>$1</em>');}};AutoComplete.prototype.matching_completions=function(text){var char,count,i,reg,_len;if(this.multiselect.options.complex_search){reg="";for(i=0,_len=text.length;i<_len;i++){char=text[i];char=text.charAt(i);reg+=RegExp.escape(char)+".*";} +reg=new RegExp(reg,"i");}else{reg=new RegExp(RegExp.escape(text),"i");} +count=0;return $.grep(this.completions,__bind(function(c){if(count>=this.multiselect.options.max_complete_results){return false;} +if($.inArray(c[1],this.multiselect.values_real())>-1){return false;} +if(c[0].match(reg)){count++;return true;}else{return false;}},this));};return AutoComplete;})();$.fn.multiselect=function(options){options!=null?options:options={};return $(this).each(function(){var completions,input,option,select_options,_i,_len,_ref;if(this.tagName.toLowerCase()==="select"){input=$(document.createElement("input"));input.attr("type","text");input.attr("name",this.name);input.attr("id",this.id);completions=[];_ref=this.options;for(_i=0,_len=_ref.length;_i<_len;_i++){option=_ref[_i];completions.push([option.innerHTML,option.value]);} +select_options={completions:completions,enable_new_options:false};$.extend(select_options,options);$(this).replaceWith(input);return new $.MultiSelect(input,select_options);}else if(this.tagName.toLowerCase()==="input"&&this.type==="text"){return new $.MultiSelect(this,options);}});};$.extend(String.prototype,{trim:function(){return this.replace(/^[\r\n\s]/g,'').replace(/[\r\n\s]$/g,'');},entitizeHTML:function(){return this.replace(/</g,'&lt;').replace(/>/g,'&gt;');},unentitizeHTML:function(){return this.replace(/&lt;/g,'<').replace(/&gt;/g,'>');},blank:function(){return this.trim().length===0;},present:function(){return!this.blank();}});return RegExp.escape=function(str){return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g,'\\$1');};})(jQuery);}).call(this); \ No newline at end of file diff --git a/js/jquery.multiselect.js b/js/jquery.multiselect.js index b72bcea..805b2f9 100644 --- a/js/jquery.multiselect.js +++ b/js/jquery.multiselect.js @@ -1,486 +1,488 @@ -var __bind = function(func, context) { - return function(){ return func.apply(context, arguments); }; - }; -(function($) { - var KEY; - KEY = { - BACKSPACE: 8, - TAB: 9, - RETURN: 13, - ESCAPE: 27, - SPACE: 32, - LEFT: 37, - UP: 38, - RIGHT: 39, - DOWN: 40, - COLON: 188, - DOT: 190 - }; - $.MultiSelect = function(element, options) { - this.options = { - separator: ",", - completions: [], - max_complete_results: 5, - enable_new_options: true, - complex_search: true +(function() { + var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; + (function($) { + var KEY; + KEY = { + BACKSPACE: 8, + TAB: 9, + RETURN: 13, + ESCAPE: 27, + SPACE: 32, + LEFT: 37, + UP: 38, + RIGHT: 39, + DOWN: 40, + COLON: 188, + DOT: 190 }; - $.extend(this.options, options || {}); - this.values = []; - this.input = $(element); - this.initialize_elements(); - this.initialize_events(); - this.parse_value(); - return this; - }; - $.MultiSelect.prototype.initialize_elements = function() { - this.hidden = $(document.createElement("input")); - this.hidden.attr("name", this.input.attr("name")); - this.hidden.attr("type", "hidden"); - this.input.removeAttr("name"); - this.container = $(document.createElement("div")); - this.container.addClass("jquery-multiselect"); - this.input_wrapper = $(document.createElement("a")); - this.input_wrapper.addClass("bit-input"); - this.input.replaceWith(this.container); - this.container.append(this.input_wrapper); - this.input_wrapper.append(this.input); - return this.container.before(this.hidden); - }; - $.MultiSelect.prototype.initialize_events = function() { - this.selection = new $.MultiSelect.Selection(this.input); - this.resizable = new $.MultiSelect.ResizableInput(this.input); - this.observer = new $.MultiSelect.InputObserver(this.input); - this.autocomplete = new $.MultiSelect.AutoComplete(this, this.options.completions); - this.input.click(__bind(function(e) { - return e.stopPropagation(); - }, this)); - this.input.keyup(__bind(function() { - return this.parse_value(1); - }, this)); - this.container.click(__bind(function() { - this.input.focus(); - return this.selection.set_caret_at_end(); - }, this)); - this.observer.bind([KEY.TAB, KEY.RETURN], __bind(function(e) { - if (this.autocomplete.val()) { - e.preventDefault(); - return this.add_and_reset(); - } - }, this)); - this.observer.bind([KEY.BACKSPACE], __bind(function(e) { - var caret; - if (this.values.length <= 0) { - return null; - } - caret = this.selection.get_caret(); - if (caret[0] === 0 && caret[1] === 0) { - e.preventDefault(); - return this.remove(this.values[this.values.length - 1]); + $.MultiSelect = (function() { + function MultiSelect(element, options) { + this.options = { + separator: ",", + completions: [], + max_complete_results: 5, + enable_new_options: true, + complex_search: true + }; + $.extend(this.options, options || {}); + this.values = []; + this.input = $(element); + this.initialize_elements(); + this.initialize_events(); + this.parse_value(); } - }, this)); - this.input.blur(__bind(function() { - return setTimeout(__bind(function() { - return this.autocomplete.hide_complete_box(); - }, this), 200); - }, this)); - return this.observer.bind([KEY.ESCAPE], __bind(function(e) { - return this.autocomplete.hide_complete_box(); - }, this)); - }; - $.MultiSelect.prototype.values_real = function() { - return $.map(this.values, function(v) { - return v[1]; - }); - }; - $.MultiSelect.prototype.parse_value = function(min) { - var _i, _len, _ref, value, values; - min = (typeof min !== "undefined" && min !== null) ? min : 0; - values = this.input.val().split(this.options.separator); - if (values.length > min) { - _ref = values; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - value = _ref[_i]; - if (value.present()) { - this.add([value, value]); + MultiSelect.prototype.initialize_elements = function() { + this.hidden = $(document.createElement("input")); + this.hidden.attr("name", this.input.attr("name")); + this.hidden.attr("type", "hidden"); + this.input.removeAttr("name"); + this.container = $(document.createElement("div")); + this.container.addClass("jquery-multiselect"); + this.input_wrapper = $(document.createElement("a")); + this.input_wrapper.addClass("bit-input"); + this.input.replaceWith(this.container); + this.container.append(this.input_wrapper); + this.input_wrapper.append(this.input); + return this.container.before(this.hidden); + }; + MultiSelect.prototype.initialize_events = function() { + this.selection = new $.MultiSelect.Selection(this.input); + this.resizable = new $.MultiSelect.ResizableInput(this.input); + this.observer = new $.MultiSelect.InputObserver(this.input); + this.autocomplete = new $.MultiSelect.AutoComplete(this, this.options.completions); + this.input.click(__bind(function(e) { + return e.stopPropagation(); + }, this)); + this.input.keyup(__bind(function() { + return this.parse_value(1); + }, this)); + this.container.click(__bind(function() { + this.input.focus(); + return this.selection.set_caret_at_end(); + }, this)); + this.observer.bind([KEY.TAB, KEY.RETURN], __bind(function(e) { + if (this.autocomplete.val()) { + e.preventDefault(); + return this.add_and_reset(); + } + }, this)); + this.observer.bind([KEY.BACKSPACE], __bind(function(e) { + var caret; + if (this.values.length <= 0) { + return; + } + caret = this.selection.get_caret(); + if (caret[0] === 0 && caret[1] === 0) { + e.preventDefault(); + return this.remove(this.values[this.values.length - 1]); + } + }, this)); + this.input.blur(__bind(function() { + return setTimeout(__bind(function() { + return this.autocomplete.hide_complete_box(); + }, this), 200); + }, this)); + return this.observer.bind([KEY.ESCAPE], __bind(function(e) { + return this.autocomplete.hide_complete_box(); + }, this)); + }; + MultiSelect.prototype.values_real = function() { + return $.map(this.values, function(v) { + return v[1]; + }); + }; + MultiSelect.prototype.parse_value = function(min) { + var value, values, _i, _len; + min != null ? min : min = 0; + values = this.input.val().split(this.options.separator); + if (values.length > min) { + for (_i = 0, _len = values.length; _i < _len; _i++) { + value = values[_i]; + if (value.present()) { + this.add([value, value]); + } + } + this.input.val(""); + return this.autocomplete.search(); } - } - this.input.val(""); - return this.autocomplete.search(); - } - }; - $.MultiSelect.prototype.add_and_reset = function() { - if (this.autocomplete.val()) { - this.add(this.autocomplete.val()); - this.input.val(""); - return this.autocomplete.search(); - } - }; - $.MultiSelect.prototype.add = function(value) { - var a, close; - if ($.inArray(value[1], this.values_real()) > -1) { - return null; - } - if (value[0].blank()) { - return null; - } - value[1] = value[1].trim(); - this.values.push(value); - a = $(document.createElement("a")); - a.addClass("bit bit-box"); - a.mouseover(function() { - return $(this).addClass("bit-hover"); - }); - a.mouseout(function() { - return $(this).removeClass("bit-hover"); - }); - a.data("value", value); - a.html(value[0].entitizeHTML()); - close = $(document.createElement("a")); - close.addClass("closebutton"); - close.click(__bind(function() { - return this.remove(a.data("value")); - }, this)); - a.append(close); - this.input_wrapper.before(a); - return this.refresh_hidden(); - }; - $.MultiSelect.prototype.remove = function(value) { - this.values = $.grep(this.values, function(v) { - return v[1] !== value[1]; - }); - this.container.find("a.bit-box").each(function() { - if ($(this).data("value")[1] === value[1]) { - return $(this).remove(); - } - }); - return this.refresh_hidden(); - }; - $.MultiSelect.prototype.refresh_hidden = function() { - return this.hidden.val(this.values_real().join(this.options.separator)); - }; - $.MultiSelect.InputObserver = function(element) { - this.input = $(element); - this.input.keydown(__bind(function(e) { - return this.handle_keydown(e); - }, this)); - this.events = []; - return this; - }; - $.MultiSelect.InputObserver.prototype.bind = function(key, callback) { - return this.events.push([key, callback]); - }; - $.MultiSelect.InputObserver.prototype.handle_keydown = function(e) { - var _i, _len, _ref, _ref2, _result, callback, event, keys; - _result = []; _ref = this.events; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - event = _ref[_i]; - _result.push((function() { - _ref2 = event; - keys = _ref2[0]; - callback = _ref2[1]; - if (!(keys.push)) { - keys = [keys]; + }; + MultiSelect.prototype.add_and_reset = function() { + if (this.autocomplete.val()) { + this.add(this.autocomplete.val()); + this.input.val(""); + return this.autocomplete.search(); } - if ($.inArray(e.keyCode, keys) > -1) { - return callback(e); + }; + MultiSelect.prototype.add = function(value) { + var a, close; + if ($.inArray(value[1], this.values_real()) > -1) { + return; } - })()); - } - return _result; - }; - $.MultiSelect.Selection = function(element) { - this.input = $(element)[0]; - return this; - }; - $.MultiSelect.Selection.prototype.get_caret = function() { - var r; - if (document.selection) { - r = document.selection.createRange().duplicate(); - r.moveEnd('character', this.input.value.length); - return r.text === '' ? [this.input.value.length, this.input.value.length] : [this.input.value.lastIndexOf(r.text), this.input.value.lastIndexOf(r.text)]; - } else { - return [this.input.selectionStart, this.input.selectionEnd]; - } - }; - $.MultiSelect.Selection.prototype.set_caret = function(begin, end) { - end = (typeof end !== "undefined" && end !== null) ? end : begin; - this.input.selectionStart = begin; - return (this.input.selectionEnd = end); - }; - $.MultiSelect.Selection.prototype.set_caret_at_end = function() { - return this.set_caret(this.input.value.length); - }; - $.MultiSelect.ResizableInput = function(element) { - this.input = $(element); - this.create_measurer(); - this.input.keypress(__bind(function(e) { - return this.set_width(e); - }, this)); - this.input.keyup(__bind(function(e) { - return this.set_width(e); - }, this)); - this.input.change(__bind(function(e) { - return this.set_width(e); - }, this)); - return this; - }; - $.MultiSelect.ResizableInput.prototype.create_measurer = function() { - var measurer; - if ($("#__jquery_multiselect_measurer")[0] === undefined) { - measurer = $(document.createElement("div")); - measurer.attr("id", "__jquery_multiselect_measurer"); - measurer.css({ - position: "absolute", - left: "-1000px", - top: "-1000px" - }); - $(document.body).append(measurer); - } - this.measurer = $("#__jquery_multiselect_measurer:first"); - return this.measurer.css({ - fontSize: this.input.css('font-size'), - fontFamily: this.input.css('font-family') - }); - }; - $.MultiSelect.ResizableInput.prototype.calculate_width = function() { - this.measurer.html(this.input.val().entitizeHTML() + 'MM'); - return this.measurer.innerWidth(); - }; - $.MultiSelect.ResizableInput.prototype.set_width = function() { - return this.input.css("width", this.calculate_width() + "px"); - }; - $.MultiSelect.AutoComplete = function(multiselect, completions) { - this.multiselect = multiselect; - this.input = this.multiselect.input; - this.completions = this.parse_completions(completions); - this.matches = []; - this.create_elements(); - this.bind_events(); - return this; - }; - $.MultiSelect.AutoComplete.prototype.parse_completions = function(completions) { - return $.map(completions, function(value) { - if (typeof value === "string") { - return [[value, value]]; - } else if (value instanceof Array && value.length === 2) { - return [value]; - } else if (value.value && value.caption) { - return [[value.caption, value.value]]; - } else { - if (console) { - return console.error("Invalid option " + (value)); + if (value[0].blank()) { + return; } - } - }); - }; - $.MultiSelect.AutoComplete.prototype.create_elements = function() { - this.container = $(document.createElement("div")); - this.container.addClass("jquery-multiselect-autocomplete"); - this.container.css("width", this.multiselect.container.outerWidth()); - this.container.css("display", "none"); - this.container.append(this.def); - this.list = $(document.createElement("ul")); - this.list.addClass("feed"); - this.container.append(this.list); - return this.multiselect.container.after(this.container); - }; - $.MultiSelect.AutoComplete.prototype.bind_events = function() { - this.input.keypress(__bind(function(e) { - return this.search(e); - }, this)); - this.input.keyup(__bind(function(e) { - return this.search(e); - }, this)); - this.input.change(__bind(function(e) { - return this.search(e); - }, this)); - this.multiselect.observer.bind(KEY.UP, __bind(function(e) { - e.preventDefault(); - return this.navigate_up(); - }, this)); - return this.multiselect.observer.bind(KEY.DOWN, __bind(function(e) { - e.preventDefault(); - return this.navigate_down(); - }, this)); - }; - $.MultiSelect.AutoComplete.prototype.search = function() { - var _i, _len, _ref, def, i; - if (this.input.val().trim() === this.query) { - return null; - } - this.query = this.input.val().trim(); - this.list.html(""); - this.current = 0; - if (this.query.present()) { - this.container.fadeIn("fast"); - this.matches = this.matching_completions(this.query); - if (this.multiselect.options.enable_new_options) { - def = this.create_item("Add <em>" + this.query + "</em>"); - def.mouseover(__bind(function(e) { - return this.select_index(0); + value[1] = value[1].trim(); + this.values.push(value); + a = $(document.createElement("a")); + a.addClass("bit bit-box"); + a.mouseover(function() { + return $(this).addClass("bit-hover"); + }); + a.mouseout(function() { + return $(this).removeClass("bit-hover"); + }); + a.data("value", value); + a.html(value[0].entitizeHTML()); + close = $(document.createElement("a")); + close.addClass("closebutton"); + close.click(__bind(function() { + return this.remove(a.data("value")); }, this)); + a.append(close); + this.input_wrapper.before(a); + return this.refresh_hidden(); + }; + MultiSelect.prototype.remove = function(value) { + this.values = $.grep(this.values, function(v) { + return v[1] !== value[1]; + }); + this.container.find("a.bit-box").each(function() { + if ($(this).data("value")[1] === value[1]) { + return $(this).remove(); + } + }); + return this.refresh_hidden(); + }; + MultiSelect.prototype.refresh_hidden = function() { + return this.hidden.val(this.values_real().join(this.options.separator)); + }; + return MultiSelect; + })(); + $.MultiSelect.InputObserver = (function() { + function InputObserver(element) { + this.input = $(element); + this.input.keydown(__bind(function(e) { + return this.handle_keydown(e); + }, this)); + this.events = []; } - _ref = this.matches; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - (function() { - var item, x; - var i = _i; - var option = _ref[_i]; - x = this.multiselect.options.enable_new_options ? i + 1 : i; - item = this.create_item(this.highlight(option[0], this.query)); - return item.mouseover(__bind(function(e) { - return this.select_index(x); - }, this)); - }).call(this); - } - if (this.multiselect.options.enable_new_options) { - this.matches.unshift([this.query, this.query]); + InputObserver.prototype.bind = function(key, callback) { + return this.events.push([key, callback]); + }; + InputObserver.prototype.handle_keydown = function(e) { + var callback, event, keys, _i, _len, _ref, _results; + _ref = this.events; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + event = _ref[_i]; + keys = event[0], callback = event[1]; + if (!keys.push) { + keys = [keys]; + } + _results.push($.inArray(e.keyCode, keys) > -1 ? callback(e) : void 0); + } + return _results; + }; + return InputObserver; + })(); + $.MultiSelect.Selection = (function() { + function Selection(element) { + this.input = $(element)[0]; } - return this.select_index(0); - } else { - this.matches = []; - this.hide_complete_box(); - return (this.query = null); - } - }; - $.MultiSelect.AutoComplete.prototype.hide_complete_box = function() { - return this.container.fadeOut("fast"); - }; - $.MultiSelect.AutoComplete.prototype.select_index = function(index) { - var items; - items = this.list.find("li"); - items.removeClass("auto-focus"); - items.filter(":eq(" + (index) + ")").addClass("auto-focus"); - return (this.current = index); - }; - $.MultiSelect.AutoComplete.prototype.navigate_down = function() { - var next; - next = this.current + 1; - if (next >= this.matches.length) { - next = 0; - } - return this.select_index(next); - }; - $.MultiSelect.AutoComplete.prototype.navigate_up = function() { - var next; - next = this.current - 1; - if (next < 0) { - next = this.matches.length - 1; - } - return this.select_index(next); - }; - $.MultiSelect.AutoComplete.prototype.create_item = function(text, highlight) { - var item; - item = $(document.createElement("li")); - item.click(__bind(function() { - this.multiselect.add_and_reset(); - this.search(); - return this.input.focus(); - }, this)); - item.html(text); - this.list.append(item); - return item; - }; - $.MultiSelect.AutoComplete.prototype.val = function() { - return this.matches[this.current]; - }; - $.MultiSelect.AutoComplete.prototype.highlight = function(text, highlight) { - var _len, _ref, char, current, highlighted, i, reg; - if (this.multiselect.options.complex_search) { - highlighted = ""; - current = 0; - _ref = text; - for (i = 0, _len = _ref.length; i < _len; i++) { - char = _ref[i]; - char = text.charAt(i); - if (current < highlight.length && char.toLowerCase() === highlight.charAt(current).toLowerCase()) { - highlighted += ("<em>" + (char) + "</em>"); - current++; + Selection.prototype.get_caret = function() { + var r; + if (document.selection) { + r = document.selection.createRange().duplicate(); + r.moveEnd('character', this.input.value.length); + if (r.text === '') { + return [this.input.value.length, this.input.value.length]; + } else { + return [this.input.value.lastIndexOf(r.text), this.input.value.lastIndexOf(r.text)]; + } } else { - highlighted += char; + return [this.input.selectionStart, this.input.selectionEnd]; } + }; + Selection.prototype.set_caret = function(begin, end) { + end != null ? end : end = begin; + this.input.selectionStart = begin; + return this.input.selectionEnd = end; + }; + Selection.prototype.set_caret_at_end = function() { + return this.set_caret(this.input.value.length); + }; + return Selection; + })(); + $.MultiSelect.ResizableInput = (function() { + function ResizableInput(element) { + this.input = $(element); + this.create_measurer(); + this.input.keypress(__bind(function(e) { + return this.set_width(e); + }, this)); + this.input.keyup(__bind(function(e) { + return this.set_width(e); + }, this)); + this.input.change(__bind(function(e) { + return this.set_width(e); + }, this)); } - return highlighted; - } else { - reg = ("(" + (RegExp.escape(highlight)) + ")"); - return text.replace(new RegExp(reg, "gi"), '<em>$1</em>'); - } - }; - $.MultiSelect.AutoComplete.prototype.matching_completions = function(text) { - var _len, _ref, char, count, i, reg; - if (this.multiselect.options.complex_search) { - reg = ""; - _ref = text; - for (i = 0, _len = _ref.length; i < _len; i++) { - char = _ref[i]; - char = text.charAt(i); - reg += RegExp.escape(char) + ".*"; - } - reg = new RegExp(reg, "i"); - } else { - reg = new RegExp(RegExp.escape(text), "i"); - } - count = 0; - return $.grep(this.completions, __bind(function(c) { - if (count >= this.multiselect.options.max_complete_results) { - return false; - } - if ($.inArray(c[1], this.multiselect.values_real()) > -1) { - return false; - } - if (c[0].match(reg)) { - count++; - return true; - } else { - return false; + ResizableInput.prototype.create_measurer = function() { + var measurer; + if ($("#__jquery_multiselect_measurer")[0] === void 0) { + measurer = $(document.createElement("div")); + measurer.attr("id", "__jquery_multiselect_measurer"); + measurer.css({ + position: "absolute", + left: "-1000px", + top: "-1000px" + }); + $(document.body).append(measurer); + } + this.measurer = $("#__jquery_multiselect_measurer:first"); + return this.measurer.css({ + fontSize: this.input.css('font-size'), + fontFamily: this.input.css('font-family') + }); + }; + ResizableInput.prototype.calculate_width = function() { + this.measurer.html(this.input.val().entitizeHTML() + 'MM'); + return this.measurer.innerWidth(); + }; + ResizableInput.prototype.set_width = function() { + return this.input.css("width", this.calculate_width() + "px"); + }; + return ResizableInput; + })(); + $.MultiSelect.AutoComplete = (function() { + function AutoComplete(multiselect, completions) { + this.multiselect = multiselect; + this.input = this.multiselect.input; + this.completions = this.parse_completions(completions); + this.matches = []; + this.create_elements(); + this.bind_events(); } - }, this)); - }; - return ($.fn.multiselect = function(options) { - options = (typeof options !== "undefined" && options !== null) ? options : {}; - return $(this).each(function() { - var _i, _len, _ref, completions, input, option, select_options; - if (this.tagName.toLowerCase() === "select") { - input = $(document.createElement("input")); - input.attr("type", "text"); - input.attr("name", this.name); - input.attr("id", this.id); - completions = []; - _ref = this.options; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - option = _ref[_i]; - completions.push([option.innerHTML, option.value]); + AutoComplete.prototype.parse_completions = function(completions) { + return $.map(completions, function(value) { + if (typeof value === "string") { + return [[value, value]]; + } else if (value instanceof Array && value.length === 2) { + return [value]; + } else if (value.value && value.caption) { + return [[value.caption, value.value]]; + } else { + if (console) { + return console.error("Invalid option " + value); + } + } + }); + }; + AutoComplete.prototype.create_elements = function() { + this.container = $(document.createElement("div")); + this.container.addClass("jquery-multiselect-autocomplete"); + this.container.css("width", this.multiselect.container.outerWidth()); + this.container.css("display", "none"); + this.container.append(this.def); + this.list = $(document.createElement("ul")); + this.list.addClass("feed"); + this.container.append(this.list); + return this.multiselect.container.after(this.container); + }; + AutoComplete.prototype.bind_events = function() { + this.input.keypress(__bind(function(e) { + return this.search(e); + }, this)); + this.input.keyup(__bind(function(e) { + return this.search(e); + }, this)); + this.input.change(__bind(function(e) { + return this.search(e); + }, this)); + this.multiselect.observer.bind(KEY.UP, __bind(function(e) { + e.preventDefault(); + return this.navigate_up(); + }, this)); + return this.multiselect.observer.bind(KEY.DOWN, __bind(function(e) { + e.preventDefault(); + return this.navigate_down(); + }, this)); + }; + AutoComplete.prototype.search = function() { + var def, i, item, option, x, _len, _ref; + if (this.input.val().trim() === this.query) { + return; } - select_options = { - completions: completions, - enable_new_options: false - }; - $.extend(select_options, options); - $(this).replaceWith(input); - return new $.MultiSelect(input, select_options); - } else if (this.tagName.toLowerCase() === "input" && this.type === "text") { - return new $.MultiSelect(this, options); + this.query = this.input.val().trim(); + this.list.html(""); + this.current = 0; + if (this.query.present()) { + this.container.fadeIn("fast"); + this.matches = this.matching_completions(this.query); + if (this.multiselect.options.enable_new_options) { + def = this.create_item("Add <em>" + this.query + "</em>"); + def.mouseover(__bind(function(e) { + return this.select_index(0); + }, this)); + } + _ref = this.matches; + for (i = 0, _len = _ref.length; i < _len; i++) { + option = _ref[i]; + x = this.multiselect.options.enable_new_options ? i + 1 : i; + item = this.create_item(this.highlight(option[0], this.query)); + item.mouseover(__bind(function(e) { + return this.select_index(x); + }, this)); + } + if (this.multiselect.options.enable_new_options) { + this.matches.unshift([this.query, this.query]); + } + return this.select_index(0); + } else { + this.matches = []; + this.hide_complete_box(); + return this.query = null; + } + }; + AutoComplete.prototype.hide_complete_box = function() { + return this.container.fadeOut("fast"); + }; + AutoComplete.prototype.select_index = function(index) { + var items; + items = this.list.find("li"); + items.removeClass("auto-focus"); + items.filter(":eq(" + index + ")").addClass("auto-focus"); + return this.current = index; + }; + AutoComplete.prototype.navigate_down = function() { + var next; + next = this.current + 1; + if (next >= this.matches.length) { + next = 0; + } + return this.select_index(next); + }; + AutoComplete.prototype.navigate_up = function() { + var next; + next = this.current - 1; + if (next < 0) { + next = this.matches.length - 1; + } + return this.select_index(next); + }; + AutoComplete.prototype.create_item = function(text, highlight) { + var item; + item = $(document.createElement("li")); + item.click(__bind(function() { + this.multiselect.add_and_reset(); + this.search(); + return this.input.focus(); + }, this)); + item.html(text); + this.list.append(item); + return item; + }; + AutoComplete.prototype.val = function() { + return this.matches[this.current]; + }; + AutoComplete.prototype.highlight = function(text, highlight) { + var char, current, highlighted, i, reg, _len; + if (this.multiselect.options.complex_search) { + highlighted = ""; + current = 0; + for (i = 0, _len = text.length; i < _len; i++) { + char = text[i]; + char = text.charAt(i); + if (current < highlight.length && char.toLowerCase() === highlight.charAt(current).toLowerCase()) { + highlighted += "<em>" + char + "</em>"; + current++; + } else { + highlighted += char; + } + } + return highlighted; + } else { + reg = "(" + (RegExp.escape(highlight)) + ")"; + return text.replace(new RegExp(reg, "gi"), '<em>$1</em>'); + } + }; + AutoComplete.prototype.matching_completions = function(text) { + var char, count, i, reg, _len; + if (this.multiselect.options.complex_search) { + reg = ""; + for (i = 0, _len = text.length; i < _len; i++) { + char = text[i]; + char = text.charAt(i); + reg += RegExp.escape(char) + ".*"; + } + reg = new RegExp(reg, "i"); + } else { + reg = new RegExp(RegExp.escape(text), "i"); + } + count = 0; + return $.grep(this.completions, __bind(function(c) { + if (count >= this.multiselect.options.max_complete_results) { + return false; + } + if ($.inArray(c[1], this.multiselect.values_real()) > -1) { + return false; + } + if (c[0].match(reg)) { + count++; + return true; + } else { + return false; + } + }, this)); + }; + return AutoComplete; + })(); + $.fn.multiselect = function(options) { + options != null ? options : options = {}; + return $(this).each(function() { + var completions, input, option, select_options, _i, _len, _ref; + if (this.tagName.toLowerCase() === "select") { + input = $(document.createElement("input")); + input.attr("type", "text"); + input.attr("name", this.name); + input.attr("id", this.id); + completions = []; + _ref = this.options; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + option = _ref[_i]; + completions.push([option.innerHTML, option.value]); + } + select_options = { + completions: completions, + enable_new_options: false + }; + $.extend(select_options, options); + $(this).replaceWith(input); + return new $.MultiSelect(input, select_options); + } else if (this.tagName.toLowerCase() === "input" && this.type === "text") { + return new $.MultiSelect(this, options); + } + }); + }; + $.extend(String.prototype, { + trim: function() { + return this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, ''); + }, + entitizeHTML: function() { + return this.replace(/</g, '&lt;').replace(/>/g, '&gt;'); + }, + unentitizeHTML: function() { + return this.replace(/&lt;/g, '<').replace(/&gt;/g, '>'); + }, + blank: function() { + return this.trim().length === 0; + }, + present: function() { + return !this.blank(); } }); - }); -})(jQuery); -$.extend(String.prototype, { - trim: function() { - return this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, ''); - }, - entitizeHTML: function() { - return this.replace(/</g, '&lt;').replace(/>/g, '&gt;'); - }, - unentitizeHTML: function() { - return this.replace(/&lt;/g, '<').replace(/&gt;/g, '>'); - }, - blank: function() { - return this.trim().length === 0; - }, - present: function() { - return !this.blank(); - } -}); -RegExp.escape = function(str) { - return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); -}; \ No newline at end of file + return RegExp.escape = function(str) { + return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); + }; + })(jQuery); +}).call(this); diff --git a/src/jquery.multiselect.coffee b/src/jquery.multiselect.coffee index 41aff54..be606fb 100644 --- a/src/jquery.multiselect.coffee +++ b/src/jquery.multiselect.coffee @@ -1,418 +1,418 @@ # Copyright (c) 2010 Wilker Lúcio # # 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. (($) -> KEY = { BACKSPACE: 8 TAB: 9 RETURN: 13 ESCAPE: 27 SPACE: 32 LEFT: 37 UP: 38 RIGHT: 39 DOWN: 40 COLON: 188 DOT: 190 } class $.MultiSelect constructor: (element, options) -> @options = { separator: "," completions: [] max_complete_results: 5 enable_new_options: true complex_search: true } $.extend(@options, options || {}) @values = [] @input = $(element) @initialize_elements() @initialize_events() @parse_value() initialize_elements: -> # hidden input to hold real value @hidden = $(document.createElement("input")) @hidden.attr("name", @input.attr("name")) @hidden.attr("type", "hidden") @input.removeAttr("name") @container = $(document.createElement("div")) @container.addClass("jquery-multiselect") @input_wrapper = $(document.createElement("a")) @input_wrapper.addClass("bit-input") @input.replaceWith(@container) @container.append(@input_wrapper) @input_wrapper.append(@input) @container.before(@hidden) initialize_events: -> # create helpers @selection = new $.MultiSelect.Selection(@input) @resizable = new $.MultiSelect.ResizableInput(@input) @observer = new $.MultiSelect.InputObserver(@input) @autocomplete = new $.MultiSelect.AutoComplete(this, @options.completions) # prevent container click to put carret at end @input.click (e) => e.stopPropagation() # create element when place separator or paste @input.keyup => @parse_value(1) # focus input and set carret at and @container.click => @input.focus() @selection.set_caret_at_end() # add element on press TAB or RETURN @observer.bind [KEY.TAB, KEY.RETURN], (e) => if @autocomplete.val() e.preventDefault() @add_and_reset() # remove last item @observer.bind [KEY.BACKSPACE], (e) => return if @values.length <= 0 caret = @selection.get_caret() if caret[0] == 0 and caret[1] == 0 e.preventDefault() @remove(@values[@values.length - 1]) # hide complete box @input.blur => setTimeout(=> @autocomplete.hide_complete_box() 200) @observer.bind [KEY.ESCAPE], (e) => @autocomplete.hide_complete_box() values_real: -> $.map @values, (v) -> v[1] parse_value: (min) -> min ?= 0 values = @input.val().split(@options.separator) if values.length > min for value in values @add [value, value] if value.present() @input.val("") @autocomplete.search() add_and_reset: -> if @autocomplete.val() @add(@autocomplete.val()) @input.val("") @autocomplete.search() # add new element add: (value) -> return if $.inArray(value[1], @values_real()) > -1 return if value[0].blank() value[1] = value[1].trim() @values.push(value) a = $(document.createElement("a")) a.addClass("bit bit-box") a.mouseover -> $(this).addClass("bit-hover") a.mouseout -> $(this).removeClass("bit-hover") a.data("value", value) a.html(value[0].entitizeHTML()) close = $(document.createElement("a")) close.addClass("closebutton") close.click => @remove(a.data("value")) a.append(close) @input_wrapper.before(a) @refresh_hidden() remove: (value) -> @values = $.grep @values, (v) -> v[1] != value[1] @container.find("a.bit-box").each -> $(this).remove() if $(this).data("value")[1] == value[1] @refresh_hidden() refresh_hidden: -> @hidden.val(@values_real().join(@options.separator)) # Input Observer Helper class $.MultiSelect.InputObserver constructor: (element) -> @input = $(element) @input.keydown (e) => @handle_keydown(e) @events = [] bind: (key, callback) -> @events.push([key, callback]) handle_keydown: (e) -> for event in @events [keys, callback] = event keys = [keys] unless keys.push callback(e) if $.inArray(e.keyCode, keys) > -1 # Selection Helper class $.MultiSelect.Selection constructor: (element) -> @input = $(element)[0] get_caret: -> # For IE if document.selection r = document.selection.createRange().duplicate() r.moveEnd('character', @input.value.length) if r.text == '' [@input.value.length, @input.value.length] else [@input.value.lastIndexOf(r.text), @input.value.lastIndexOf(r.text)] # Others else [@input.selectionStart, @input.selectionEnd] set_caret: (begin, end) -> end ?= begin @input.selectionStart = begin @input.selectionEnd = end set_caret_at_end: -> @set_caret(@input.value.length) # Resizable Input Helper class $.MultiSelect.ResizableInput constructor: (element) -> @input = $(element) @create_measurer() @input.keypress (e) => @set_width(e) @input.keyup (e) => @set_width(e) @input.change (e) => @set_width(e) create_measurer: -> if $("#__jquery_multiselect_measurer")[0] == undefined measurer = $(document.createElement("div")) measurer.attr("id", "__jquery_multiselect_measurer") measurer.css { position: "absolute" left: "-1000px" top: "-1000px" } $(document.body).append(measurer) @measurer = $("#__jquery_multiselect_measurer:first") @measurer.css { fontSize: @input.css('font-size') fontFamily: @input.css('font-family') } calculate_width: -> @measurer.html(@input.val().entitizeHTML() + 'MM') @measurer.innerWidth() set_width: -> @input.css("width", @calculate_width() + "px") # AutoComplete Helper class $.MultiSelect.AutoComplete constructor: (multiselect, completions) -> @multiselect = multiselect @input = @multiselect.input @completions = @parse_completions(completions) @matches = [] @create_elements() @bind_events() parse_completions: (completions) -> $.map completions, (value) -> if typeof value == "string" [[value, value]] else if value instanceof Array and value.length == 2 [value] else if value.value and value.caption [[value.caption, value.value]] else console.error "Invalid option #{value}" if console create_elements: -> @container = $(document.createElement("div")) @container.addClass("jquery-multiselect-autocomplete") @container.css("width", @multiselect.container.outerWidth()) @container.css("display", "none") @container.append(@def) @list = $(document.createElement("ul")) @list.addClass("feed") @container.append(@list) @multiselect.container.after(@container) bind_events: -> @input.keypress (e) => @search(e) @input.keyup (e) => @search(e) @input.change (e) => @search(e) @multiselect.observer.bind KEY.UP, (e) => e.preventDefault(); @navigate_up() @multiselect.observer.bind KEY.DOWN, (e) => e.preventDefault(); @navigate_down() search: -> return if @input.val().trim() == @query # dont do operation if query is same @query = @input.val().trim() @list.html("") # clear list @current = 0 if @query.present() @container.fadeIn("fast") @matches = @matching_completions(@query) if @multiselect.options.enable_new_options def = @create_item("Add <em>" + @query + "</em>") def.mouseover (e) => @select_index(0) for option, i in @matches x = if @multiselect.options.enable_new_options then i + 1 else i item = @create_item(@highlight(option[0], @query)) item.mouseover (e) => @select_index(x) @matches.unshift([@query, @query]) if @multiselect.options.enable_new_options @select_index(0) else @matches = [] @hide_complete_box() @query = null hide_complete_box: -> @container.fadeOut("fast") select_index: (index) -> items = @list.find("li") items.removeClass("auto-focus") items.filter(":eq(#{index})").addClass("auto-focus") @current = index navigate_down: -> next = @current + 1 next = 0 if next >= @matches.length @select_index(next) navigate_up: -> next = @current - 1 next = @matches.length - 1 if next < 0 @select_index(next) create_item: (text, highlight) -> item = $(document.createElement("li")) item.click => @multiselect.add_and_reset() @search() @input.focus() item.html(text) @list.append(item) item val: -> @matches[@current] highlight: (text, highlight) -> if @multiselect.options.complex_search highlighted = "" current = 0 for char, i in text char = text.charAt(i) if current < highlight.length and char.toLowerCase() == highlight.charAt(current).toLowerCase() highlighted += "<em>#{char}</em>" current++ else highlighted += char highlighted else reg = "(#{RegExp.escape(highlight)})" text.replace(new RegExp(reg, "gi"), '<em>$1</em>') matching_completions: (text) -> if @multiselect.options.complex_search reg = "" for char, i in text char = text.charAt(i) reg += RegExp.escape(char) + ".*" reg = new RegExp(reg, "i") else reg = new RegExp(RegExp.escape(text), "i") count = 0 $.grep @completions, (c) => return false if count >= @multiselect.options.max_complete_results return false if $.inArray(c[1], @multiselect.values_real()) > -1 if c[0].match(reg) count++ true else false # Hook jQuery extension $.fn.multiselect = (options) -> options ?= {} $(this).each -> if this.tagName.toLowerCase() == "select" input = $(document.createElement("input")) input.attr("type", "text") input.attr("name", this.name) input.attr("id", this.id) completions = [] for option in this.options completions.push([option.innerHTML, option.value]) select_options = { completions: completions enable_new_options: false } $.extend(select_options, options) $(this).replaceWith(input) new $.MultiSelect(input, select_options) else if this.tagName.toLowerCase() == "input" and this.type == "text" new $.MultiSelect(this, options) -)(jQuery) -$.extend String.prototype, { - trim: -> this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, '') - entitizeHTML: -> this.replace(/</g,'&lt;').replace(/>/g,'&gt;') - unentitizeHTML: -> this.replace(/&lt;/g,'<').replace(/&gt;/g,'>') - blank: -> this.trim().length == 0 - present: -> not @blank() -} + $.extend String.prototype, { + trim: -> this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, '') + entitizeHTML: -> this.replace(/</g,'&lt;').replace(/>/g,'&gt;') + unentitizeHTML: -> this.replace(/&lt;/g,'<').replace(/&gt;/g,'>') + blank: -> this.trim().length == 0 + present: -> not @blank() + } -RegExp.escape = (str) -> - String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); + RegExp.escape = (str) -> + String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1') +)(jQuery)
wilkerlucio/jquery-multiselect
baac8e884c39e63a269d4111753267bd4166d8c7
fixed mouse selection
diff --git a/js/jquery.multiselect.js b/js/jquery.multiselect.js index ab07f0f..b72bcea 100644 --- a/js/jquery.multiselect.js +++ b/js/jquery.multiselect.js @@ -1,486 +1,486 @@ var __bind = function(func, context) { return function(){ return func.apply(context, arguments); }; }; (function($) { var KEY; KEY = { BACKSPACE: 8, TAB: 9, RETURN: 13, ESCAPE: 27, SPACE: 32, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, COLON: 188, DOT: 190 }; $.MultiSelect = function(element, options) { this.options = { separator: ",", completions: [], max_complete_results: 5, enable_new_options: true, complex_search: true }; $.extend(this.options, options || {}); this.values = []; this.input = $(element); this.initialize_elements(); this.initialize_events(); this.parse_value(); return this; }; $.MultiSelect.prototype.initialize_elements = function() { this.hidden = $(document.createElement("input")); this.hidden.attr("name", this.input.attr("name")); this.hidden.attr("type", "hidden"); this.input.removeAttr("name"); this.container = $(document.createElement("div")); this.container.addClass("jquery-multiselect"); this.input_wrapper = $(document.createElement("a")); this.input_wrapper.addClass("bit-input"); this.input.replaceWith(this.container); this.container.append(this.input_wrapper); this.input_wrapper.append(this.input); return this.container.before(this.hidden); }; $.MultiSelect.prototype.initialize_events = function() { this.selection = new $.MultiSelect.Selection(this.input); this.resizable = new $.MultiSelect.ResizableInput(this.input); this.observer = new $.MultiSelect.InputObserver(this.input); this.autocomplete = new $.MultiSelect.AutoComplete(this, this.options.completions); this.input.click(__bind(function(e) { return e.stopPropagation(); }, this)); this.input.keyup(__bind(function() { return this.parse_value(1); }, this)); this.container.click(__bind(function() { this.input.focus(); return this.selection.set_caret_at_end(); }, this)); this.observer.bind([KEY.TAB, KEY.RETURN], __bind(function(e) { if (this.autocomplete.val()) { e.preventDefault(); return this.add_and_reset(); } }, this)); this.observer.bind([KEY.BACKSPACE], __bind(function(e) { var caret; if (this.values.length <= 0) { return null; } caret = this.selection.get_caret(); if (caret[0] === 0 && caret[1] === 0) { e.preventDefault(); return this.remove(this.values[this.values.length - 1]); } }, this)); this.input.blur(__bind(function() { return setTimeout(__bind(function() { return this.autocomplete.hide_complete_box(); }, this), 200); }, this)); return this.observer.bind([KEY.ESCAPE], __bind(function(e) { return this.autocomplete.hide_complete_box(); }, this)); }; $.MultiSelect.prototype.values_real = function() { return $.map(this.values, function(v) { return v[1]; }); }; $.MultiSelect.prototype.parse_value = function(min) { var _i, _len, _ref, value, values; min = (typeof min !== "undefined" && min !== null) ? min : 0; values = this.input.val().split(this.options.separator); if (values.length > min) { _ref = values; for (_i = 0, _len = _ref.length; _i < _len; _i++) { value = _ref[_i]; if (value.present()) { this.add([value, value]); } } this.input.val(""); return this.autocomplete.search(); } }; $.MultiSelect.prototype.add_and_reset = function() { if (this.autocomplete.val()) { this.add(this.autocomplete.val()); this.input.val(""); return this.autocomplete.search(); } }; $.MultiSelect.prototype.add = function(value) { var a, close; if ($.inArray(value[1], this.values_real()) > -1) { return null; } if (value[0].blank()) { return null; } value[1] = value[1].trim(); this.values.push(value); a = $(document.createElement("a")); a.addClass("bit bit-box"); a.mouseover(function() { return $(this).addClass("bit-hover"); }); a.mouseout(function() { return $(this).removeClass("bit-hover"); }); a.data("value", value); a.html(value[0].entitizeHTML()); close = $(document.createElement("a")); close.addClass("closebutton"); close.click(__bind(function() { return this.remove(a.data("value")); }, this)); a.append(close); this.input_wrapper.before(a); return this.refresh_hidden(); }; $.MultiSelect.prototype.remove = function(value) { this.values = $.grep(this.values, function(v) { return v[1] !== value[1]; }); this.container.find("a.bit-box").each(function() { if ($(this).data("value")[1] === value[1]) { return $(this).remove(); } }); return this.refresh_hidden(); }; $.MultiSelect.prototype.refresh_hidden = function() { return this.hidden.val(this.values_real().join(this.options.separator)); }; $.MultiSelect.InputObserver = function(element) { this.input = $(element); this.input.keydown(__bind(function(e) { return this.handle_keydown(e); }, this)); this.events = []; return this; }; $.MultiSelect.InputObserver.prototype.bind = function(key, callback) { return this.events.push([key, callback]); }; $.MultiSelect.InputObserver.prototype.handle_keydown = function(e) { var _i, _len, _ref, _ref2, _result, callback, event, keys; _result = []; _ref = this.events; for (_i = 0, _len = _ref.length; _i < _len; _i++) { event = _ref[_i]; _result.push((function() { _ref2 = event; keys = _ref2[0]; callback = _ref2[1]; if (!(keys.push)) { keys = [keys]; } if ($.inArray(e.keyCode, keys) > -1) { return callback(e); } })()); } return _result; }; $.MultiSelect.Selection = function(element) { this.input = $(element)[0]; return this; }; $.MultiSelect.Selection.prototype.get_caret = function() { var r; if (document.selection) { r = document.selection.createRange().duplicate(); r.moveEnd('character', this.input.value.length); return r.text === '' ? [this.input.value.length, this.input.value.length] : [this.input.value.lastIndexOf(r.text), this.input.value.lastIndexOf(r.text)]; } else { return [this.input.selectionStart, this.input.selectionEnd]; } }; $.MultiSelect.Selection.prototype.set_caret = function(begin, end) { end = (typeof end !== "undefined" && end !== null) ? end : begin; this.input.selectionStart = begin; return (this.input.selectionEnd = end); }; $.MultiSelect.Selection.prototype.set_caret_at_end = function() { return this.set_caret(this.input.value.length); }; $.MultiSelect.ResizableInput = function(element) { this.input = $(element); this.create_measurer(); this.input.keypress(__bind(function(e) { return this.set_width(e); }, this)); this.input.keyup(__bind(function(e) { return this.set_width(e); }, this)); this.input.change(__bind(function(e) { return this.set_width(e); }, this)); return this; }; $.MultiSelect.ResizableInput.prototype.create_measurer = function() { var measurer; if ($("#__jquery_multiselect_measurer")[0] === undefined) { measurer = $(document.createElement("div")); measurer.attr("id", "__jquery_multiselect_measurer"); measurer.css({ position: "absolute", left: "-1000px", top: "-1000px" }); $(document.body).append(measurer); } this.measurer = $("#__jquery_multiselect_measurer:first"); return this.measurer.css({ fontSize: this.input.css('font-size'), fontFamily: this.input.css('font-family') }); }; $.MultiSelect.ResizableInput.prototype.calculate_width = function() { this.measurer.html(this.input.val().entitizeHTML() + 'MM'); return this.measurer.innerWidth(); }; $.MultiSelect.ResizableInput.prototype.set_width = function() { return this.input.css("width", this.calculate_width() + "px"); }; $.MultiSelect.AutoComplete = function(multiselect, completions) { this.multiselect = multiselect; this.input = this.multiselect.input; this.completions = this.parse_completions(completions); this.matches = []; this.create_elements(); this.bind_events(); return this; }; $.MultiSelect.AutoComplete.prototype.parse_completions = function(completions) { return $.map(completions, function(value) { if (typeof value === "string") { return [[value, value]]; } else if (value instanceof Array && value.length === 2) { return [value]; } else if (value.value && value.caption) { return [[value.caption, value.value]]; } else { if (console) { return console.error("Invalid option " + (value)); } } }); }; $.MultiSelect.AutoComplete.prototype.create_elements = function() { this.container = $(document.createElement("div")); this.container.addClass("jquery-multiselect-autocomplete"); this.container.css("width", this.multiselect.container.outerWidth()); this.container.css("display", "none"); this.container.append(this.def); this.list = $(document.createElement("ul")); this.list.addClass("feed"); this.container.append(this.list); return this.multiselect.container.after(this.container); }; $.MultiSelect.AutoComplete.prototype.bind_events = function() { this.input.keypress(__bind(function(e) { return this.search(e); }, this)); this.input.keyup(__bind(function(e) { return this.search(e); }, this)); this.input.change(__bind(function(e) { return this.search(e); }, this)); this.multiselect.observer.bind(KEY.UP, __bind(function(e) { e.preventDefault(); return this.navigate_up(); }, this)); return this.multiselect.observer.bind(KEY.DOWN, __bind(function(e) { e.preventDefault(); return this.navigate_down(); }, this)); }; $.MultiSelect.AutoComplete.prototype.search = function() { var _i, _len, _ref, def, i; if (this.input.val().trim() === this.query) { return null; } this.query = this.input.val().trim(); this.list.html(""); this.current = 0; if (this.query.present()) { this.container.fadeIn("fast"); this.matches = this.matching_completions(this.query); if (this.multiselect.options.enable_new_options) { def = this.create_item("Add <em>" + this.query + "</em>"); def.mouseover(__bind(function(e) { - return this.select_index(e, 0); + return this.select_index(0); }, this)); } _ref = this.matches; for (_i = 0, _len = _ref.length; _i < _len; _i++) { (function() { var item, x; var i = _i; var option = _ref[_i]; x = this.multiselect.options.enable_new_options ? i + 1 : i; item = this.create_item(this.highlight(option[0], this.query)); return item.mouseover(__bind(function(e) { - return this.select_index(e, x); + return this.select_index(x); }, this)); }).call(this); } if (this.multiselect.options.enable_new_options) { this.matches.unshift([this.query, this.query]); } return this.select_index(0); } else { this.matches = []; this.hide_complete_box(); return (this.query = null); } }; $.MultiSelect.AutoComplete.prototype.hide_complete_box = function() { return this.container.fadeOut("fast"); }; $.MultiSelect.AutoComplete.prototype.select_index = function(index) { var items; items = this.list.find("li"); items.removeClass("auto-focus"); items.filter(":eq(" + (index) + ")").addClass("auto-focus"); return (this.current = index); }; $.MultiSelect.AutoComplete.prototype.navigate_down = function() { var next; next = this.current + 1; if (next >= this.matches.length) { next = 0; } return this.select_index(next); }; $.MultiSelect.AutoComplete.prototype.navigate_up = function() { var next; next = this.current - 1; if (next < 0) { next = this.matches.length - 1; } return this.select_index(next); }; $.MultiSelect.AutoComplete.prototype.create_item = function(text, highlight) { var item; item = $(document.createElement("li")); item.click(__bind(function() { this.multiselect.add_and_reset(); this.search(); return this.input.focus(); }, this)); item.html(text); this.list.append(item); return item; }; $.MultiSelect.AutoComplete.prototype.val = function() { return this.matches[this.current]; }; $.MultiSelect.AutoComplete.prototype.highlight = function(text, highlight) { var _len, _ref, char, current, highlighted, i, reg; if (this.multiselect.options.complex_search) { highlighted = ""; current = 0; _ref = text; for (i = 0, _len = _ref.length; i < _len; i++) { char = _ref[i]; char = text.charAt(i); if (current < highlight.length && char.toLowerCase() === highlight.charAt(current).toLowerCase()) { highlighted += ("<em>" + (char) + "</em>"); current++; } else { highlighted += char; } } return highlighted; } else { reg = ("(" + (RegExp.escape(highlight)) + ")"); return text.replace(new RegExp(reg, "gi"), '<em>$1</em>'); } }; $.MultiSelect.AutoComplete.prototype.matching_completions = function(text) { var _len, _ref, char, count, i, reg; if (this.multiselect.options.complex_search) { reg = ""; _ref = text; for (i = 0, _len = _ref.length; i < _len; i++) { char = _ref[i]; char = text.charAt(i); reg += RegExp.escape(char) + ".*"; } reg = new RegExp(reg, "i"); } else { reg = new RegExp(RegExp.escape(text), "i"); } count = 0; return $.grep(this.completions, __bind(function(c) { if (count >= this.multiselect.options.max_complete_results) { return false; } if ($.inArray(c[1], this.multiselect.values_real()) > -1) { return false; } if (c[0].match(reg)) { count++; return true; } else { return false; } }, this)); }; return ($.fn.multiselect = function(options) { options = (typeof options !== "undefined" && options !== null) ? options : {}; return $(this).each(function() { var _i, _len, _ref, completions, input, option, select_options; if (this.tagName.toLowerCase() === "select") { input = $(document.createElement("input")); input.attr("type", "text"); input.attr("name", this.name); input.attr("id", this.id); completions = []; _ref = this.options; for (_i = 0, _len = _ref.length; _i < _len; _i++) { option = _ref[_i]; completions.push([option.innerHTML, option.value]); } select_options = { completions: completions, enable_new_options: false }; $.extend(select_options, options); $(this).replaceWith(input); return new $.MultiSelect(input, select_options); } else if (this.tagName.toLowerCase() === "input" && this.type === "text") { return new $.MultiSelect(this, options); } }); }); })(jQuery); $.extend(String.prototype, { trim: function() { return this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, ''); }, entitizeHTML: function() { return this.replace(/</g, '&lt;').replace(/>/g, '&gt;'); }, unentitizeHTML: function() { return this.replace(/&lt;/g, '<').replace(/&gt;/g, '>'); }, blank: function() { return this.trim().length === 0; }, present: function() { return !this.blank(); } }); RegExp.escape = function(str) { return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); }; \ No newline at end of file diff --git a/src/jquery.multiselect.coffee b/src/jquery.multiselect.coffee index ea05996..41aff54 100644 --- a/src/jquery.multiselect.coffee +++ b/src/jquery.multiselect.coffee @@ -1,418 +1,418 @@ # Copyright (c) 2010 Wilker Lúcio # # 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. (($) -> KEY = { BACKSPACE: 8 TAB: 9 RETURN: 13 ESCAPE: 27 SPACE: 32 LEFT: 37 UP: 38 RIGHT: 39 DOWN: 40 COLON: 188 DOT: 190 } class $.MultiSelect constructor: (element, options) -> @options = { separator: "," completions: [] max_complete_results: 5 enable_new_options: true complex_search: true } $.extend(@options, options || {}) @values = [] @input = $(element) @initialize_elements() @initialize_events() @parse_value() initialize_elements: -> # hidden input to hold real value @hidden = $(document.createElement("input")) @hidden.attr("name", @input.attr("name")) @hidden.attr("type", "hidden") @input.removeAttr("name") @container = $(document.createElement("div")) @container.addClass("jquery-multiselect") @input_wrapper = $(document.createElement("a")) @input_wrapper.addClass("bit-input") @input.replaceWith(@container) @container.append(@input_wrapper) @input_wrapper.append(@input) @container.before(@hidden) initialize_events: -> # create helpers @selection = new $.MultiSelect.Selection(@input) @resizable = new $.MultiSelect.ResizableInput(@input) @observer = new $.MultiSelect.InputObserver(@input) @autocomplete = new $.MultiSelect.AutoComplete(this, @options.completions) # prevent container click to put carret at end @input.click (e) => e.stopPropagation() # create element when place separator or paste @input.keyup => @parse_value(1) # focus input and set carret at and @container.click => @input.focus() @selection.set_caret_at_end() # add element on press TAB or RETURN @observer.bind [KEY.TAB, KEY.RETURN], (e) => if @autocomplete.val() e.preventDefault() @add_and_reset() # remove last item @observer.bind [KEY.BACKSPACE], (e) => return if @values.length <= 0 caret = @selection.get_caret() if caret[0] == 0 and caret[1] == 0 e.preventDefault() @remove(@values[@values.length - 1]) # hide complete box @input.blur => setTimeout(=> @autocomplete.hide_complete_box() 200) @observer.bind [KEY.ESCAPE], (e) => @autocomplete.hide_complete_box() values_real: -> $.map @values, (v) -> v[1] parse_value: (min) -> min ?= 0 values = @input.val().split(@options.separator) if values.length > min for value in values @add [value, value] if value.present() @input.val("") @autocomplete.search() add_and_reset: -> if @autocomplete.val() @add(@autocomplete.val()) @input.val("") @autocomplete.search() # add new element add: (value) -> return if $.inArray(value[1], @values_real()) > -1 return if value[0].blank() value[1] = value[1].trim() @values.push(value) a = $(document.createElement("a")) a.addClass("bit bit-box") a.mouseover -> $(this).addClass("bit-hover") a.mouseout -> $(this).removeClass("bit-hover") a.data("value", value) a.html(value[0].entitizeHTML()) close = $(document.createElement("a")) close.addClass("closebutton") close.click => @remove(a.data("value")) a.append(close) @input_wrapper.before(a) @refresh_hidden() remove: (value) -> @values = $.grep @values, (v) -> v[1] != value[1] @container.find("a.bit-box").each -> $(this).remove() if $(this).data("value")[1] == value[1] @refresh_hidden() refresh_hidden: -> @hidden.val(@values_real().join(@options.separator)) # Input Observer Helper class $.MultiSelect.InputObserver constructor: (element) -> @input = $(element) @input.keydown (e) => @handle_keydown(e) @events = [] bind: (key, callback) -> @events.push([key, callback]) handle_keydown: (e) -> for event in @events [keys, callback] = event keys = [keys] unless keys.push callback(e) if $.inArray(e.keyCode, keys) > -1 # Selection Helper class $.MultiSelect.Selection constructor: (element) -> @input = $(element)[0] get_caret: -> # For IE if document.selection r = document.selection.createRange().duplicate() r.moveEnd('character', @input.value.length) if r.text == '' [@input.value.length, @input.value.length] else [@input.value.lastIndexOf(r.text), @input.value.lastIndexOf(r.text)] # Others else [@input.selectionStart, @input.selectionEnd] set_caret: (begin, end) -> end ?= begin @input.selectionStart = begin @input.selectionEnd = end set_caret_at_end: -> @set_caret(@input.value.length) # Resizable Input Helper class $.MultiSelect.ResizableInput constructor: (element) -> @input = $(element) @create_measurer() @input.keypress (e) => @set_width(e) @input.keyup (e) => @set_width(e) @input.change (e) => @set_width(e) create_measurer: -> if $("#__jquery_multiselect_measurer")[0] == undefined measurer = $(document.createElement("div")) measurer.attr("id", "__jquery_multiselect_measurer") measurer.css { position: "absolute" left: "-1000px" top: "-1000px" } $(document.body).append(measurer) @measurer = $("#__jquery_multiselect_measurer:first") @measurer.css { fontSize: @input.css('font-size') fontFamily: @input.css('font-family') } calculate_width: -> @measurer.html(@input.val().entitizeHTML() + 'MM') @measurer.innerWidth() set_width: -> @input.css("width", @calculate_width() + "px") # AutoComplete Helper class $.MultiSelect.AutoComplete constructor: (multiselect, completions) -> @multiselect = multiselect @input = @multiselect.input @completions = @parse_completions(completions) @matches = [] @create_elements() @bind_events() parse_completions: (completions) -> $.map completions, (value) -> if typeof value == "string" [[value, value]] else if value instanceof Array and value.length == 2 [value] else if value.value and value.caption [[value.caption, value.value]] else console.error "Invalid option #{value}" if console create_elements: -> @container = $(document.createElement("div")) @container.addClass("jquery-multiselect-autocomplete") @container.css("width", @multiselect.container.outerWidth()) @container.css("display", "none") @container.append(@def) @list = $(document.createElement("ul")) @list.addClass("feed") @container.append(@list) @multiselect.container.after(@container) bind_events: -> @input.keypress (e) => @search(e) @input.keyup (e) => @search(e) @input.change (e) => @search(e) @multiselect.observer.bind KEY.UP, (e) => e.preventDefault(); @navigate_up() @multiselect.observer.bind KEY.DOWN, (e) => e.preventDefault(); @navigate_down() search: -> return if @input.val().trim() == @query # dont do operation if query is same @query = @input.val().trim() @list.html("") # clear list @current = 0 if @query.present() @container.fadeIn("fast") @matches = @matching_completions(@query) if @multiselect.options.enable_new_options def = @create_item("Add <em>" + @query + "</em>") - def.mouseover (e) => @select_index(e, 0) + def.mouseover (e) => @select_index(0) for option, i in @matches x = if @multiselect.options.enable_new_options then i + 1 else i item = @create_item(@highlight(option[0], @query)) - item.mouseover (e) => @select_index(e, x) + item.mouseover (e) => @select_index(x) @matches.unshift([@query, @query]) if @multiselect.options.enable_new_options @select_index(0) else @matches = [] @hide_complete_box() @query = null hide_complete_box: -> @container.fadeOut("fast") select_index: (index) -> items = @list.find("li") items.removeClass("auto-focus") items.filter(":eq(#{index})").addClass("auto-focus") @current = index navigate_down: -> next = @current + 1 next = 0 if next >= @matches.length @select_index(next) navigate_up: -> next = @current - 1 next = @matches.length - 1 if next < 0 @select_index(next) create_item: (text, highlight) -> item = $(document.createElement("li")) item.click => @multiselect.add_and_reset() @search() @input.focus() item.html(text) @list.append(item) item val: -> @matches[@current] highlight: (text, highlight) -> if @multiselect.options.complex_search highlighted = "" current = 0 for char, i in text char = text.charAt(i) if current < highlight.length and char.toLowerCase() == highlight.charAt(current).toLowerCase() highlighted += "<em>#{char}</em>" current++ else highlighted += char highlighted else reg = "(#{RegExp.escape(highlight)})" text.replace(new RegExp(reg, "gi"), '<em>$1</em>') matching_completions: (text) -> if @multiselect.options.complex_search reg = "" for char, i in text char = text.charAt(i) reg += RegExp.escape(char) + ".*" reg = new RegExp(reg, "i") else reg = new RegExp(RegExp.escape(text), "i") count = 0 $.grep @completions, (c) => return false if count >= @multiselect.options.max_complete_results return false if $.inArray(c[1], @multiselect.values_real()) > -1 if c[0].match(reg) count++ true else false # Hook jQuery extension $.fn.multiselect = (options) -> options ?= {} $(this).each -> if this.tagName.toLowerCase() == "select" input = $(document.createElement("input")) input.attr("type", "text") input.attr("name", this.name) input.attr("id", this.id) completions = [] for option in this.options completions.push([option.innerHTML, option.value]) select_options = { completions: completions enable_new_options: false } $.extend(select_options, options) $(this).replaceWith(input) new $.MultiSelect(input, select_options) else if this.tagName.toLowerCase() == "input" and this.type == "text" new $.MultiSelect(this, options) )(jQuery) $.extend String.prototype, { trim: -> this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, '') entitizeHTML: -> this.replace(/</g,'&lt;').replace(/>/g,'&gt;') unentitizeHTML: -> this.replace(/&lt;/g,'<').replace(/&gt;/g,'>') blank: -> this.trim().length == 0 present: -> not @blank() } RegExp.escape = (str) -> String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
wilkerlucio/jquery-multiselect
23d2fce202ee3e29b9ede291ffe6f5a26fdcd4cf
gemfile lock
diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..b705e5b --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,10 @@ +GEM + remote: http://rubygems.org/ + specs: + jsmin (1.0.1) + +PLATFORMS + ruby + +DEPENDENCIES + jsmin
wilkerlucio/jquery-multiselect
db96237e09c0553d64ceb169d638c4811315ba8f
ported code for coffeescript 0.9.4
diff --git a/js/jquery.multiselect.js b/js/jquery.multiselect.js index 093b046..ab07f0f 100644 --- a/js/jquery.multiselect.js +++ b/js/jquery.multiselect.js @@ -1,599 +1,486 @@ -// Copyright (c) 2010 Wilker Lúcio -// -// 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. +var __bind = function(func, context) { + return function(){ return func.apply(context, arguments); }; + }; (function($) { var KEY; KEY = { BACKSPACE: 8, TAB: 9, RETURN: 13, ESCAPE: 27, SPACE: 32, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, COLON: 188, DOT: 190 }; - $.MultiSelect = function MultiSelect(element, options) { + $.MultiSelect = function(element, options) { this.options = { separator: ",", completions: [], max_complete_results: 5, enable_new_options: true, complex_search: true }; $.extend(this.options, options || {}); this.values = []; this.input = $(element); this.initialize_elements(); this.initialize_events(); this.parse_value(); return this; }; - $.MultiSelect.prototype.initialize_elements = function initialize_elements() { - // hidden input to hold real value + $.MultiSelect.prototype.initialize_elements = function() { this.hidden = $(document.createElement("input")); this.hidden.attr("name", this.input.attr("name")); this.hidden.attr("type", "hidden"); this.input.removeAttr("name"); this.container = $(document.createElement("div")); this.container.addClass("jquery-multiselect"); this.input_wrapper = $(document.createElement("a")); this.input_wrapper.addClass("bit-input"); this.input.replaceWith(this.container); this.container.append(this.input_wrapper); this.input_wrapper.append(this.input); return this.container.before(this.hidden); }; - $.MultiSelect.prototype.initialize_events = function initialize_events() { - // create helpers + $.MultiSelect.prototype.initialize_events = function() { this.selection = new $.MultiSelect.Selection(this.input); this.resizable = new $.MultiSelect.ResizableInput(this.input); this.observer = new $.MultiSelect.InputObserver(this.input); this.autocomplete = new $.MultiSelect.AutoComplete(this, this.options.completions); - // prevent container click to put carret at end - this.input.click((function(__this) { - var __func = function(e) { - return e.stopPropagation(); - }; - return (function() { - return __func.apply(__this, arguments); - }); - })(this)); - // create element when place separator or paste - this.input.keyup((function(__this) { - var __func = function() { - return this.parse_value(1); - }; - return (function() { - return __func.apply(__this, arguments); - }); - })(this)); - // focus input and set carret at and - this.container.click((function(__this) { - var __func = function() { - this.input.focus(); - return this.selection.set_caret_at_end(); - }; - return (function() { - return __func.apply(__this, arguments); - }); - })(this)); - // add element on press TAB or RETURN - this.observer.bind([KEY.TAB, KEY.RETURN], (function(__this) { - var __func = function(e) { - if (this.autocomplete.val()) { - e.preventDefault(); - return this.add_and_reset(); - } - }; - return (function() { - return __func.apply(__this, arguments); - }); - })(this)); - // remove last item - this.observer.bind([KEY.BACKSPACE], (function(__this) { - var __func = function(e) { - var caret; - if (this.values.length <= 0) { - return null; - } - caret = this.selection.get_caret(); - if (caret[0] === 0 && caret[1] === 0) { - e.preventDefault(); - return this.remove(this.values[this.values.length - 1]); - } - }; - return (function() { - return __func.apply(__this, arguments); - }); - })(this)); - // hide complete box - this.input.blur((function(__this) { - var __func = function() { - return setTimeout((function(__this) { - var __func = function() { - return this.autocomplete.hide_complete_box(); - }; - return (function() { - return __func.apply(__this, arguments); - }); - })(this), 200); - }; - return (function() { - return __func.apply(__this, arguments); - }); - })(this)); - return this.observer.bind([KEY.ESCAPE], (function(__this) { - var __func = function(e) { + this.input.click(__bind(function(e) { + return e.stopPropagation(); + }, this)); + this.input.keyup(__bind(function() { + return this.parse_value(1); + }, this)); + this.container.click(__bind(function() { + this.input.focus(); + return this.selection.set_caret_at_end(); + }, this)); + this.observer.bind([KEY.TAB, KEY.RETURN], __bind(function(e) { + if (this.autocomplete.val()) { + e.preventDefault(); + return this.add_and_reset(); + } + }, this)); + this.observer.bind([KEY.BACKSPACE], __bind(function(e) { + var caret; + if (this.values.length <= 0) { + return null; + } + caret = this.selection.get_caret(); + if (caret[0] === 0 && caret[1] === 0) { + e.preventDefault(); + return this.remove(this.values[this.values.length - 1]); + } + }, this)); + this.input.blur(__bind(function() { + return setTimeout(__bind(function() { return this.autocomplete.hide_complete_box(); - }; - return (function() { - return __func.apply(__this, arguments); - }); - })(this)); + }, this), 200); + }, this)); + return this.observer.bind([KEY.ESCAPE], __bind(function(e) { + return this.autocomplete.hide_complete_box(); + }, this)); }; - $.MultiSelect.prototype.values_real = function values_real() { + $.MultiSelect.prototype.values_real = function() { return $.map(this.values, function(v) { return v[1]; }); }; - $.MultiSelect.prototype.parse_value = function parse_value(min) { - var _a, _b, _c, value, values; + $.MultiSelect.prototype.parse_value = function(min) { + var _i, _len, _ref, value, values; min = (typeof min !== "undefined" && min !== null) ? min : 0; values = this.input.val().split(this.options.separator); if (values.length > min) { - _b = values; - for (_a = 0, _c = _b.length; _a < _c; _a++) { - value = _b[_a]; + _ref = values; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + value = _ref[_i]; if (value.present()) { this.add([value, value]); } } this.input.val(""); return this.autocomplete.search(); } }; - $.MultiSelect.prototype.add_and_reset = function add_and_reset() { + $.MultiSelect.prototype.add_and_reset = function() { if (this.autocomplete.val()) { this.add(this.autocomplete.val()); this.input.val(""); return this.autocomplete.search(); } }; - // add new element - $.MultiSelect.prototype.add = function add(value) { + $.MultiSelect.prototype.add = function(value) { var a, close; if ($.inArray(value[1], this.values_real()) > -1) { return null; } if (value[0].blank()) { return null; } value[1] = value[1].trim(); this.values.push(value); a = $(document.createElement("a")); a.addClass("bit bit-box"); a.mouseover(function() { return $(this).addClass("bit-hover"); }); a.mouseout(function() { return $(this).removeClass("bit-hover"); }); a.data("value", value); a.html(value[0].entitizeHTML()); close = $(document.createElement("a")); close.addClass("closebutton"); - close.click((function(__this) { - var __func = function() { - return this.remove(a.data("value")); - }; - return (function() { - return __func.apply(__this, arguments); - }); - })(this)); + close.click(__bind(function() { + return this.remove(a.data("value")); + }, this)); a.append(close); this.input_wrapper.before(a); return this.refresh_hidden(); }; - $.MultiSelect.prototype.remove = function remove(value) { + $.MultiSelect.prototype.remove = function(value) { this.values = $.grep(this.values, function(v) { return v[1] !== value[1]; }); this.container.find("a.bit-box").each(function() { if ($(this).data("value")[1] === value[1]) { return $(this).remove(); } }); return this.refresh_hidden(); }; - $.MultiSelect.prototype.refresh_hidden = function refresh_hidden() { + $.MultiSelect.prototype.refresh_hidden = function() { return this.hidden.val(this.values_real().join(this.options.separator)); }; - // Input Observer Helper - $.MultiSelect.InputObserver = function InputObserver(element) { + $.MultiSelect.InputObserver = function(element) { this.input = $(element); - this.input.keydown((function(func, obj, args) { - return function() { - return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); - }; - }(this.handle_keydown, this, []))); + this.input.keydown(__bind(function(e) { + return this.handle_keydown(e); + }, this)); this.events = []; return this; }; - $.MultiSelect.InputObserver.prototype.bind = function bind(key, callback) { + $.MultiSelect.InputObserver.prototype.bind = function(key, callback) { return this.events.push([key, callback]); }; - $.MultiSelect.InputObserver.prototype.handle_keydown = function handle_keydown(e) { - var _a, _b, _c, _d, _e, callback, event, keys; - _a = []; _c = this.events; - for (_b = 0, _d = _c.length; _b < _d; _b++) { - event = _c[_b]; - _a.push((function() { - _e = event; - keys = _e[0]; - callback = _e[1]; + $.MultiSelect.InputObserver.prototype.handle_keydown = function(e) { + var _i, _len, _ref, _ref2, _result, callback, event, keys; + _result = []; _ref = this.events; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + event = _ref[_i]; + _result.push((function() { + _ref2 = event; + keys = _ref2[0]; + callback = _ref2[1]; if (!(keys.push)) { keys = [keys]; } if ($.inArray(e.keyCode, keys) > -1) { return callback(e); } - }).call(this)); + })()); } - return _a; + return _result; }; - // Selection Helper - $.MultiSelect.Selection = function Selection(element) { + $.MultiSelect.Selection = function(element) { this.input = $(element)[0]; return this; }; - $.MultiSelect.Selection.prototype.get_caret = function get_caret() { + $.MultiSelect.Selection.prototype.get_caret = function() { var r; - // For IE if (document.selection) { r = document.selection.createRange().duplicate(); r.moveEnd('character', this.input.value.length); - if (r.text === '') { - return [this.input.value.length, this.input.value.length]; - } else { - return [this.input.value.lastIndexOf(r.text), this.input.value.lastIndexOf(r.text)]; - // Others - } + return r.text === '' ? [this.input.value.length, this.input.value.length] : [this.input.value.lastIndexOf(r.text), this.input.value.lastIndexOf(r.text)]; } else { return [this.input.selectionStart, this.input.selectionEnd]; } }; - $.MultiSelect.Selection.prototype.set_caret = function set_caret(begin, end) { + $.MultiSelect.Selection.prototype.set_caret = function(begin, end) { end = (typeof end !== "undefined" && end !== null) ? end : begin; this.input.selectionStart = begin; - this.input.selectionEnd = end; - return this.input.selectionEnd; + return (this.input.selectionEnd = end); }; - $.MultiSelect.Selection.prototype.set_caret_at_end = function set_caret_at_end() { + $.MultiSelect.Selection.prototype.set_caret_at_end = function() { return this.set_caret(this.input.value.length); }; - // Resizable Input Helper - $.MultiSelect.ResizableInput = function ResizableInput(element) { + $.MultiSelect.ResizableInput = function(element) { this.input = $(element); this.create_measurer(); - this.input.keypress((function(func, obj, args) { - return function() { - return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); - }; - }(this.set_width, this, []))); - this.input.keyup((function(func, obj, args) { - return function() { - return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); - }; - }(this.set_width, this, []))); - this.input.change((function(func, obj, args) { - return function() { - return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); - }; - }(this.set_width, this, []))); + this.input.keypress(__bind(function(e) { + return this.set_width(e); + }, this)); + this.input.keyup(__bind(function(e) { + return this.set_width(e); + }, this)); + this.input.change(__bind(function(e) { + return this.set_width(e); + }, this)); return this; }; - $.MultiSelect.ResizableInput.prototype.create_measurer = function create_measurer() { + $.MultiSelect.ResizableInput.prototype.create_measurer = function() { var measurer; if ($("#__jquery_multiselect_measurer")[0] === undefined) { measurer = $(document.createElement("div")); measurer.attr("id", "__jquery_multiselect_measurer"); measurer.css({ position: "absolute", left: "-1000px", top: "-1000px" }); $(document.body).append(measurer); } this.measurer = $("#__jquery_multiselect_measurer:first"); return this.measurer.css({ fontSize: this.input.css('font-size'), fontFamily: this.input.css('font-family') }); }; - $.MultiSelect.ResizableInput.prototype.calculate_width = function calculate_width() { + $.MultiSelect.ResizableInput.prototype.calculate_width = function() { this.measurer.html(this.input.val().entitizeHTML() + 'MM'); return this.measurer.innerWidth(); }; - $.MultiSelect.ResizableInput.prototype.set_width = function set_width() { + $.MultiSelect.ResizableInput.prototype.set_width = function() { return this.input.css("width", this.calculate_width() + "px"); }; - // AutoComplete Helper - $.MultiSelect.AutoComplete = function AutoComplete(multiselect, completions) { + $.MultiSelect.AutoComplete = function(multiselect, completions) { this.multiselect = multiselect; this.input = this.multiselect.input; this.completions = this.parse_completions(completions); this.matches = []; this.create_elements(); this.bind_events(); return this; }; - $.MultiSelect.AutoComplete.prototype.parse_completions = function parse_completions(completions) { + $.MultiSelect.AutoComplete.prototype.parse_completions = function(completions) { return $.map(completions, function(value) { if (typeof value === "string") { return [[value, value]]; } else if (value instanceof Array && value.length === 2) { return [value]; } else if (value.value && value.caption) { return [[value.caption, value.value]]; - } else if (console) { - return console.error("Invalid option " + (value)); + } else { + if (console) { + return console.error("Invalid option " + (value)); + } } }); }; - $.MultiSelect.AutoComplete.prototype.create_elements = function create_elements() { + $.MultiSelect.AutoComplete.prototype.create_elements = function() { this.container = $(document.createElement("div")); this.container.addClass("jquery-multiselect-autocomplete"); this.container.css("width", this.multiselect.container.outerWidth()); this.container.css("display", "none"); this.container.append(this.def); this.list = $(document.createElement("ul")); this.list.addClass("feed"); this.container.append(this.list); return this.multiselect.container.after(this.container); }; - $.MultiSelect.AutoComplete.prototype.bind_events = function bind_events() { - this.input.keypress((function(func, obj, args) { - return function() { - return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); - }; - }(this.search, this, []))); - this.input.keyup((function(func, obj, args) { - return function() { - return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); - }; - }(this.search, this, []))); - this.input.change((function(func, obj, args) { - return function() { - return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); - }; - }(this.search, this, []))); - this.multiselect.observer.bind(KEY.UP, (function(__this) { - var __func = function(e) { - e.preventDefault(); - return this.navigate_up(); - }; - return (function() { - return __func.apply(__this, arguments); - }); - })(this)); - return this.multiselect.observer.bind(KEY.DOWN, (function(__this) { - var __func = function(e) { - e.preventDefault(); - return this.navigate_down(); - }; - return (function() { - return __func.apply(__this, arguments); - }); - })(this)); - }; - $.MultiSelect.AutoComplete.prototype.search = function search() { - var _a, _b, def, i, item, option, x; + $.MultiSelect.AutoComplete.prototype.bind_events = function() { + this.input.keypress(__bind(function(e) { + return this.search(e); + }, this)); + this.input.keyup(__bind(function(e) { + return this.search(e); + }, this)); + this.input.change(__bind(function(e) { + return this.search(e); + }, this)); + this.multiselect.observer.bind(KEY.UP, __bind(function(e) { + e.preventDefault(); + return this.navigate_up(); + }, this)); + return this.multiselect.observer.bind(KEY.DOWN, __bind(function(e) { + e.preventDefault(); + return this.navigate_down(); + }, this)); + }; + $.MultiSelect.AutoComplete.prototype.search = function() { + var _i, _len, _ref, def, i; if (this.input.val().trim() === this.query) { return null; } - // dont do operation if query is same this.query = this.input.val().trim(); this.list.html(""); - // clear list this.current = 0; if (this.query.present()) { this.container.fadeIn("fast"); this.matches = this.matching_completions(this.query); if (this.multiselect.options.enable_new_options) { def = this.create_item("Add <em>" + this.query + "</em>"); - def.mouseover((function(func, obj, args) { - return function() { - return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); - }; - }(this.select_index, this, [0]))); + def.mouseover(__bind(function(e) { + return this.select_index(e, 0); + }, this)); } - _a = this.matches; - for (i = 0, _b = _a.length; i < _b; i++) { - option = _a[i]; - x = this.multiselect.options.enable_new_options ? i + 1 : i; - item = this.create_item(this.highlight(option[0], this.query)); - item.mouseover((function(func, obj, args) { - return function() { - return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); - }; - }(this.select_index, this, [x]))); + _ref = this.matches; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + (function() { + var item, x; + var i = _i; + var option = _ref[_i]; + x = this.multiselect.options.enable_new_options ? i + 1 : i; + item = this.create_item(this.highlight(option[0], this.query)); + return item.mouseover(__bind(function(e) { + return this.select_index(e, x); + }, this)); + }).call(this); } if (this.multiselect.options.enable_new_options) { this.matches.unshift([this.query, this.query]); } return this.select_index(0); } else { this.matches = []; this.hide_complete_box(); - this.query = null; - return this.query; + return (this.query = null); } }; - $.MultiSelect.AutoComplete.prototype.hide_complete_box = function hide_complete_box() { + $.MultiSelect.AutoComplete.prototype.hide_complete_box = function() { return this.container.fadeOut("fast"); }; - $.MultiSelect.AutoComplete.prototype.select_index = function select_index(index) { + $.MultiSelect.AutoComplete.prototype.select_index = function(index) { var items; items = this.list.find("li"); items.removeClass("auto-focus"); items.filter(":eq(" + (index) + ")").addClass("auto-focus"); - this.current = index; - return this.current; + return (this.current = index); }; - $.MultiSelect.AutoComplete.prototype.navigate_down = function navigate_down() { + $.MultiSelect.AutoComplete.prototype.navigate_down = function() { var next; next = this.current + 1; if (next >= this.matches.length) { next = 0; } return this.select_index(next); }; - $.MultiSelect.AutoComplete.prototype.navigate_up = function navigate_up() { + $.MultiSelect.AutoComplete.prototype.navigate_up = function() { var next; next = this.current - 1; if (next < 0) { next = this.matches.length - 1; } return this.select_index(next); }; - $.MultiSelect.AutoComplete.prototype.create_item = function create_item(text, highlight) { + $.MultiSelect.AutoComplete.prototype.create_item = function(text, highlight) { var item; item = $(document.createElement("li")); - item.click((function(__this) { - var __func = function() { - this.multiselect.add_and_reset(); - this.search(); - return this.input.focus(); - }; - return (function() { - return __func.apply(__this, arguments); - }); - })(this)); + item.click(__bind(function() { + this.multiselect.add_and_reset(); + this.search(); + return this.input.focus(); + }, this)); item.html(text); this.list.append(item); return item; }; - $.MultiSelect.AutoComplete.prototype.val = function val() { + $.MultiSelect.AutoComplete.prototype.val = function() { return this.matches[this.current]; }; - $.MultiSelect.AutoComplete.prototype.highlight = function highlight(text, highlight) { - var _a, _b, char, current, highlighted, i, reg; + $.MultiSelect.AutoComplete.prototype.highlight = function(text, highlight) { + var _len, _ref, char, current, highlighted, i, reg; if (this.multiselect.options.complex_search) { highlighted = ""; current = 0; - _a = text; - for (i = 0, _b = _a.length; i < _b; i++) { - char = _a[i]; + _ref = text; + for (i = 0, _len = _ref.length; i < _len; i++) { + char = _ref[i]; char = text.charAt(i); if (current < highlight.length && char.toLowerCase() === highlight.charAt(current).toLowerCase()) { - highlighted += "<em>" + (char) + "</em>"; + highlighted += ("<em>" + (char) + "</em>"); current++; } else { highlighted += char; } } return highlighted; } else { - reg = "(" + (RegExp.escape(highlight)) + ")"; + reg = ("(" + (RegExp.escape(highlight)) + ")"); return text.replace(new RegExp(reg, "gi"), '<em>$1</em>'); } }; - $.MultiSelect.AutoComplete.prototype.matching_completions = function matching_completions(text) { - var _a, _b, char, count, i, reg; + $.MultiSelect.AutoComplete.prototype.matching_completions = function(text) { + var _len, _ref, char, count, i, reg; if (this.multiselect.options.complex_search) { reg = ""; - _a = text; - for (i = 0, _b = _a.length; i < _b; i++) { - char = _a[i]; + _ref = text; + for (i = 0, _len = _ref.length; i < _len; i++) { + char = _ref[i]; char = text.charAt(i); reg += RegExp.escape(char) + ".*"; } reg = new RegExp(reg, "i"); } else { reg = new RegExp(RegExp.escape(text), "i"); } count = 0; - return $.grep(this.completions, (function(__this) { - var __func = function(c) { - if (count >= this.multiselect.options.max_complete_results) { - return false; - } - if ($.inArray(c[1], this.multiselect.values_real()) > -1) { - return false; - } - if (c[0].match(reg)) { - count++; - return true; - } else { - return false; - } - }; - return (function() { - return __func.apply(__this, arguments); - }); - })(this)); + return $.grep(this.completions, __bind(function(c) { + if (count >= this.multiselect.options.max_complete_results) { + return false; + } + if ($.inArray(c[1], this.multiselect.values_real()) > -1) { + return false; + } + if (c[0].match(reg)) { + count++; + return true; + } else { + return false; + } + }, this)); }; - // Hook jQuery extension - $.fn.multiselect = function multiselect(options) { + return ($.fn.multiselect = function(options) { options = (typeof options !== "undefined" && options !== null) ? options : {}; return $(this).each(function() { - var _a, _b, _c, completions, input, option, select_options; + var _i, _len, _ref, completions, input, option, select_options; if (this.tagName.toLowerCase() === "select") { input = $(document.createElement("input")); input.attr("type", "text"); input.attr("name", this.name); input.attr("id", this.id); completions = []; - _b = this.options; - for (_a = 0, _c = _b.length; _a < _c; _a++) { - option = _b[_a]; + _ref = this.options; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + option = _ref[_i]; completions.push([option.innerHTML, option.value]); } select_options = { completions: completions, enable_new_options: false }; $.extend(select_options, options); $(this).replaceWith(input); return new $.MultiSelect(input, select_options); } else if (this.tagName.toLowerCase() === "input" && this.type === "text") { return new $.MultiSelect(this, options); } }); - }; - return $.fn.multiselect; + }); })(jQuery); $.extend(String.prototype, { - trim: function trim() { + trim: function() { return this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, ''); }, - entitizeHTML: function entitizeHTML() { + entitizeHTML: function() { return this.replace(/</g, '&lt;').replace(/>/g, '&gt;'); }, - unentitizeHTML: function unentitizeHTML() { + unentitizeHTML: function() { return this.replace(/&lt;/g, '<').replace(/&gt;/g, '>'); }, - blank: function blank() { + blank: function() { return this.trim().length === 0; }, - present: function present() { + present: function() { return !this.blank(); } }); -RegExp.escape = function escape(str) { +RegExp.escape = function(str) { return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); }; \ No newline at end of file diff --git a/src/jquery.multiselect.coffee b/src/jquery.multiselect.coffee index 4768460..ea05996 100644 --- a/src/jquery.multiselect.coffee +++ b/src/jquery.multiselect.coffee @@ -1,418 +1,418 @@ # Copyright (c) 2010 Wilker Lúcio -# +# # 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. (($) -> - KEY: { + KEY = { BACKSPACE: 8 TAB: 9 RETURN: 13 ESCAPE: 27 SPACE: 32 LEFT: 37 UP: 38 RIGHT: 39 DOWN: 40 COLON: 188 DOT: 190 } - + class $.MultiSelect constructor: (element, options) -> - @options: { + @options = { separator: "," completions: [] max_complete_results: 5 enable_new_options: true complex_search: true } $.extend(@options, options || {}) - @values: [] - @input: $(element) + @values = [] + @input = $(element) @initialize_elements() @initialize_events() @parse_value() - + initialize_elements: -> # hidden input to hold real value - @hidden: $(document.createElement("input")) + @hidden = $(document.createElement("input")) @hidden.attr("name", @input.attr("name")) @hidden.attr("type", "hidden") @input.removeAttr("name") - - @container: $(document.createElement("div")) + + @container = $(document.createElement("div")) @container.addClass("jquery-multiselect") - - @input_wrapper: $(document.createElement("a")) + + @input_wrapper = $(document.createElement("a")) @input_wrapper.addClass("bit-input") - + @input.replaceWith(@container) @container.append(@input_wrapper) @input_wrapper.append(@input) @container.before(@hidden) - + initialize_events: -> # create helpers - @selection: new $.MultiSelect.Selection(@input) - @resizable: new $.MultiSelect.ResizableInput(@input) - @observer: new $.MultiSelect.InputObserver(@input) - @autocomplete: new $.MultiSelect.AutoComplete(this, @options.completions) - + @selection = new $.MultiSelect.Selection(@input) + @resizable = new $.MultiSelect.ResizableInput(@input) + @observer = new $.MultiSelect.InputObserver(@input) + @autocomplete = new $.MultiSelect.AutoComplete(this, @options.completions) + # prevent container click to put carret at end @input.click (e) => e.stopPropagation() - + # create element when place separator or paste @input.keyup => @parse_value(1) - + # focus input and set carret at and @container.click => @input.focus() @selection.set_caret_at_end() - + # add element on press TAB or RETURN @observer.bind [KEY.TAB, KEY.RETURN], (e) => if @autocomplete.val() e.preventDefault() @add_and_reset() - + # remove last item @observer.bind [KEY.BACKSPACE], (e) => return if @values.length <= 0 caret = @selection.get_caret() - + if caret[0] == 0 and caret[1] == 0 e.preventDefault() @remove(@values[@values.length - 1]) - + # hide complete box @input.blur => setTimeout(=> @autocomplete.hide_complete_box() 200) - + @observer.bind [KEY.ESCAPE], (e) => @autocomplete.hide_complete_box() - + values_real: -> $.map @values, (v) -> v[1] - + parse_value: (min) -> min ?= 0 - values: @input.val().split(@options.separator) + values = @input.val().split(@options.separator) if values.length > min for value in values @add [value, value] if value.present() @input.val("") @autocomplete.search() - + add_and_reset: -> if @autocomplete.val() @add(@autocomplete.val()) @input.val("") @autocomplete.search() - + # add new element add: (value) -> return if $.inArray(value[1], @values_real()) > -1 return if value[0].blank() - + value[1] = value[1].trim() @values.push(value) - - a: $(document.createElement("a")) + + a = $(document.createElement("a")) a.addClass("bit bit-box") a.mouseover -> $(this).addClass("bit-hover") a.mouseout -> $(this).removeClass("bit-hover") a.data("value", value) a.html(value[0].entitizeHTML()) - - close: $(document.createElement("a")) + + close = $(document.createElement("a")) close.addClass("closebutton") close.click => @remove(a.data("value")) a.append(close) - + @input_wrapper.before(a) @refresh_hidden() - + remove: (value) -> - @values: $.grep @values, (v) -> v[1] != value[1] + @values = $.grep @values, (v) -> v[1] != value[1] @container.find("a.bit-box").each -> $(this).remove() if $(this).data("value")[1] == value[1] @refresh_hidden() - + refresh_hidden: -> @hidden.val(@values_real().join(@options.separator)) - + # Input Observer Helper class $.MultiSelect.InputObserver constructor: (element) -> - @input: $(element) - @input.keydown(@handle_keydown <- this) - @events: [] - + @input = $(element) + @input.keydown (e) => @handle_keydown(e) + @events = [] + bind: (key, callback) -> @events.push([key, callback]) - + handle_keydown: (e) -> for event in @events - [keys, callback]: event - keys: [keys] unless keys.push + [keys, callback] = event + keys = [keys] unless keys.push callback(e) if $.inArray(e.keyCode, keys) > -1 - + # Selection Helper class $.MultiSelect.Selection constructor: (element) -> - @input: $(element)[0] - + @input = $(element)[0] + get_caret: -> # For IE if document.selection - r: document.selection.createRange().duplicate() + r = document.selection.createRange().duplicate() r.moveEnd('character', @input.value.length) - + if r.text == '' [@input.value.length, @input.value.length] else [@input.value.lastIndexOf(r.text), @input.value.lastIndexOf(r.text)] # Others else [@input.selectionStart, @input.selectionEnd] - + set_caret: (begin, end) -> end ?= begin - @input.selectionStart: begin - @input.selectionEnd: end - + @input.selectionStart = begin + @input.selectionEnd = end + set_caret_at_end: -> @set_caret(@input.value.length) - + # Resizable Input Helper class $.MultiSelect.ResizableInput constructor: (element) -> - @input: $(element) + @input = $(element) @create_measurer() - @input.keypress(@set_width <- this) - @input.keyup(@set_width <- this) - @input.change(@set_width <- this) - + @input.keypress (e) => @set_width(e) + @input.keyup (e) => @set_width(e) + @input.change (e) => @set_width(e) + create_measurer: -> if $("#__jquery_multiselect_measurer")[0] == undefined - measurer: $(document.createElement("div")) + measurer = $(document.createElement("div")) measurer.attr("id", "__jquery_multiselect_measurer") measurer.css { position: "absolute" left: "-1000px" top: "-1000px" } - + $(document.body).append(measurer) - - @measurer: $("#__jquery_multiselect_measurer:first") + + @measurer = $("#__jquery_multiselect_measurer:first") @measurer.css { fontSize: @input.css('font-size') fontFamily: @input.css('font-family') } - - calculate_width: -> + + calculate_width: -> @measurer.html(@input.val().entitizeHTML() + 'MM') @measurer.innerWidth() - + set_width: -> @input.css("width", @calculate_width() + "px") - + # AutoComplete Helper class $.MultiSelect.AutoComplete constructor: (multiselect, completions) -> - @multiselect: multiselect - @input: @multiselect.input - @completions: @parse_completions(completions) - @matches: [] + @multiselect = multiselect + @input = @multiselect.input + @completions = @parse_completions(completions) + @matches = [] @create_elements() @bind_events() - + parse_completions: (completions) -> $.map completions, (value) -> if typeof value == "string" [[value, value]] else if value instanceof Array and value.length == 2 [value] else if value.value and value.caption [[value.caption, value.value]] else - console.error "Invalid option ${value}" if console - + console.error "Invalid option #{value}" if console + create_elements: -> - @container: $(document.createElement("div")) + @container = $(document.createElement("div")) @container.addClass("jquery-multiselect-autocomplete") @container.css("width", @multiselect.container.outerWidth()) @container.css("display", "none") - + @container.append(@def) - - @list: $(document.createElement("ul")) + + @list = $(document.createElement("ul")) @list.addClass("feed") - + @container.append(@list) @multiselect.container.after(@container) - + bind_events: -> - @input.keypress(@search <- this) - @input.keyup(@search <- this) - @input.change(@search <- this) + @input.keypress (e) => @search(e) + @input.keyup (e) => @search(e) + @input.change (e) => @search(e) @multiselect.observer.bind KEY.UP, (e) => e.preventDefault(); @navigate_up() @multiselect.observer.bind KEY.DOWN, (e) => e.preventDefault(); @navigate_down() - + search: -> return if @input.val().trim() == @query # dont do operation if query is same - - @query: @input.val().trim() + + @query = @input.val().trim() @list.html("") # clear list - @current: 0 - + @current = 0 + if @query.present() @container.fadeIn("fast") - @matches: @matching_completions(@query) - + @matches = @matching_completions(@query) + if @multiselect.options.enable_new_options - def: @create_item("Add <em>" + @query + "</em>") - def.mouseover(@select_index <- this, 0) - + def = @create_item("Add <em>" + @query + "</em>") + def.mouseover (e) => @select_index(e, 0) + for option, i in @matches - x: if @multiselect.options.enable_new_options then i + 1 else i - item: @create_item(@highlight(option[0], @query)) - item.mouseover(@select_index <- this, x) - + x = if @multiselect.options.enable_new_options then i + 1 else i + item = @create_item(@highlight(option[0], @query)) + item.mouseover (e) => @select_index(e, x) + @matches.unshift([@query, @query]) if @multiselect.options.enable_new_options - + @select_index(0) else - @matches: [] + @matches = [] @hide_complete_box() - @query: null - + @query = null + hide_complete_box: -> @container.fadeOut("fast") - + select_index: (index) -> - items: @list.find("li") + items = @list.find("li") items.removeClass("auto-focus") - items.filter(":eq(${index})").addClass("auto-focus") - - @current: index - + items.filter(":eq(#{index})").addClass("auto-focus") + + @current = index + navigate_down: -> - next: @current + 1 - next: 0 if next >= @matches.length + next = @current + 1 + next = 0 if next >= @matches.length @select_index(next) - + navigate_up: -> - next: @current - 1 - next: @matches.length - 1 if next < 0 + next = @current - 1 + next = @matches.length - 1 if next < 0 @select_index(next) - + create_item: (text, highlight) -> - item: $(document.createElement("li")) + item = $(document.createElement("li")) item.click => @multiselect.add_and_reset() @search() @input.focus() item.html(text) @list.append(item) item - + val: -> @matches[@current] - + highlight: (text, highlight) -> if @multiselect.options.complex_search - highlighted: "" - current: 0 - + highlighted = "" + current = 0 + for char, i in text - char: text.charAt(i) + char = text.charAt(i) if current < highlight.length and char.toLowerCase() == highlight.charAt(current).toLowerCase() - highlighted += "<em>${char}</em>" + highlighted += "<em>#{char}</em>" current++ else highlighted += char - + highlighted else - reg: "(${RegExp.escape(highlight)})" + reg = "(#{RegExp.escape(highlight)})" text.replace(new RegExp(reg, "gi"), '<em>$1</em>') - + matching_completions: (text) -> if @multiselect.options.complex_search - reg: "" + reg = "" for char, i in text - char: text.charAt(i) + char = text.charAt(i) reg += RegExp.escape(char) + ".*" - - reg: new RegExp(reg, "i") + + reg = new RegExp(reg, "i") else - reg: new RegExp(RegExp.escape(text), "i") - count: 0 + reg = new RegExp(RegExp.escape(text), "i") + count = 0 $.grep @completions, (c) => return false if count >= @multiselect.options.max_complete_results return false if $.inArray(c[1], @multiselect.values_real()) > -1 - + if c[0].match(reg) count++ true else false - + # Hook jQuery extension - $.fn.multiselect: (options) -> + $.fn.multiselect = (options) -> options ?= {} - + $(this).each -> if this.tagName.toLowerCase() == "select" - input: $(document.createElement("input")) + input = $(document.createElement("input")) input.attr("type", "text") input.attr("name", this.name) input.attr("id", this.id) - - completions: [] + + completions = [] for option in this.options completions.push([option.innerHTML, option.value]) - - select_options: { + + select_options = { completions: completions enable_new_options: false } - + $.extend(select_options, options) - + $(this).replaceWith(input) - + new $.MultiSelect(input, select_options) else if this.tagName.toLowerCase() == "input" and this.type == "text" new $.MultiSelect(this, options) )(jQuery) $.extend String.prototype, { trim: -> this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, '') entitizeHTML: -> this.replace(/</g,'&lt;').replace(/>/g,'&gt;') unentitizeHTML: -> this.replace(/&lt;/g,'<').replace(/&gt;/g,'>') blank: -> this.trim().length == 0 present: -> not @blank() -}; +} -RegExp.escape: (str) -> +RegExp.escape = (str) -> String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
wilkerlucio/jquery-multiselect
520ab2de1521d24bbebe2f822b919818f2725784
fixing rake file
diff --git a/Rakefile b/Rakefile index 8bd2e17..e962539 100644 --- a/Rakefile +++ b/Rakefile @@ -1,44 +1,45 @@ +# encoding: utf-8 require 'rubygems' require 'bundler' Bundler.setup Bundler.require desc "Compile CoffeeScripts and watch for changes" task :coffee do - coffee = IO.popen 'coffee -wc --no-wrap src/*.coffee -o js 2>&1' - + coffee = IO.popen 'coffee -wc --no-wrap -o js src/*.coffee 2>&1' + while line = coffee.gets puts line end end desc "Build minified version" task :build do content = File.read("js/jquery.multiselect.js") minyfied = JSMin.minify(content) version = File.read("VERSION") - + licence = <<LIC /** * Copyright (c) 2010 Wilker Lúcio * * 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. */ LIC - + File.open("dist/jquery.multiselect.#{version}.min.js", "wb") do |f| f << licence f << minyfied end -end \ No newline at end of file +end
wilkerlucio/jquery-multiselect
c79f667d16e9ddf303fd72ebed90ab778bd37d65
released 0.1.7
diff --git a/VERSION b/VERSION index a192233..a1e1395 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.1.6 \ No newline at end of file +0.1.7 \ No newline at end of file diff --git a/dist/jquery.multiselect.0.1.7.min.js b/dist/jquery.multiselect.0.1.7.min.js new file mode 100644 index 0000000..76dded1 --- /dev/null +++ b/dist/jquery.multiselect.0.1.7.min.js @@ -0,0 +1,36 @@ +/** + * Copyright (c) 2010 Wilker Lúcio + * + * 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. + */ + +(function($){var KEY;KEY={BACKSPACE:8,TAB:9,RETURN:13,ESCAPE:27,SPACE:32,LEFT:37,UP:38,RIGHT:39,DOWN:40,COLON:188,DOT:190};$.MultiSelect=function MultiSelect(element,options){this.options={separator:",",completions:[],max_complete_results:5,enable_new_options:true,complex_search:true};$.extend(this.options,options||{});this.values=[];this.input=$(element);this.initialize_elements();this.initialize_events();this.parse_value();return this;};$.MultiSelect.prototype.initialize_elements=function initialize_elements(){this.hidden=$(document.createElement("input"));this.hidden.attr("name",this.input.attr("name"));this.hidden.attr("type","hidden");this.input.removeAttr("name");this.container=$(document.createElement("div"));this.container.addClass("jquery-multiselect");this.input_wrapper=$(document.createElement("a"));this.input_wrapper.addClass("bit-input");this.input.replaceWith(this.container);this.container.append(this.input_wrapper);this.input_wrapper.append(this.input);return this.container.before(this.hidden);};$.MultiSelect.prototype.initialize_events=function initialize_events(){this.selection=new $.MultiSelect.Selection(this.input);this.resizable=new $.MultiSelect.ResizableInput(this.input);this.observer=new $.MultiSelect.InputObserver(this.input);this.autocomplete=new $.MultiSelect.AutoComplete(this,this.options.completions);this.input.click((function(__this){var __func=function(e){return e.stopPropagation();};return(function(){return __func.apply(__this,arguments);});})(this));this.input.keyup((function(__this){var __func=function(){return this.parse_value(1);};return(function(){return __func.apply(__this,arguments);});})(this));this.container.click((function(__this){var __func=function(){this.input.focus();return this.selection.set_caret_at_end();};return(function(){return __func.apply(__this,arguments);});})(this));this.observer.bind([KEY.TAB,KEY.RETURN],(function(__this){var __func=function(e){if(this.autocomplete.val()){e.preventDefault();return this.add_and_reset();}};return(function(){return __func.apply(__this,arguments);});})(this));this.observer.bind([KEY.BACKSPACE],(function(__this){var __func=function(e){var caret;if(this.values.length<=0){return null;} +caret=this.selection.get_caret();if(caret[0]===0&&caret[1]===0){e.preventDefault();return this.remove(this.values[this.values.length-1]);}};return(function(){return __func.apply(__this,arguments);});})(this));this.input.blur((function(__this){var __func=function(){return setTimeout((function(__this){var __func=function(){return this.autocomplete.hide_complete_box();};return(function(){return __func.apply(__this,arguments);});})(this),200);};return(function(){return __func.apply(__this,arguments);});})(this));return this.observer.bind([KEY.ESCAPE],(function(__this){var __func=function(e){return this.autocomplete.hide_complete_box();};return(function(){return __func.apply(__this,arguments);});})(this));};$.MultiSelect.prototype.values_real=function values_real(){return $.map(this.values,function(v){return v[1];});};$.MultiSelect.prototype.parse_value=function parse_value(min){var _a,_b,_c,value,values;min=(typeof min!=="undefined"&&min!==null)?min:0;values=this.input.val().split(this.options.separator);if(values.length>min){_b=values;for(_a=0,_c=_b.length;_a<_c;_a++){value=_b[_a];if(value.present()){this.add([value,value]);}} +this.input.val("");return this.autocomplete.search();}};$.MultiSelect.prototype.add_and_reset=function add_and_reset(){if(this.autocomplete.val()){this.add(this.autocomplete.val());this.input.val("");return this.autocomplete.search();}};$.MultiSelect.prototype.add=function add(value){var a,close;if($.inArray(value[1],this.values_real())>-1){return null;} +if(value[0].blank()){return null;} +value[1]=value[1].trim();this.values.push(value);a=$(document.createElement("a"));a.addClass("bit bit-box");a.mouseover(function(){return $(this).addClass("bit-hover");});a.mouseout(function(){return $(this).removeClass("bit-hover");});a.data("value",value);a.html(value[0].entitizeHTML());close=$(document.createElement("a"));close.addClass("closebutton");close.click((function(__this){var __func=function(){return this.remove(a.data("value"));};return(function(){return __func.apply(__this,arguments);});})(this));a.append(close);this.input_wrapper.before(a);return this.refresh_hidden();};$.MultiSelect.prototype.remove=function remove(value){this.values=$.grep(this.values,function(v){return v[1]!==value[1];});this.container.find("a.bit-box").each(function(){if($(this).data("value")[1]===value[1]){return $(this).remove();}});return this.refresh_hidden();};$.MultiSelect.prototype.refresh_hidden=function refresh_hidden(){return this.hidden.val(this.values_real().join(this.options.separator));};$.MultiSelect.InputObserver=function InputObserver(element){this.input=$(element);this.input.keydown((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.handle_keydown,this,[])));this.events=[];return this;};$.MultiSelect.InputObserver.prototype.bind=function bind(key,callback){return this.events.push([key,callback]);};$.MultiSelect.InputObserver.prototype.handle_keydown=function handle_keydown(e){var _a,_b,_c,_d,_e,callback,event,keys;_a=[];_c=this.events;for(_b=0,_d=_c.length;_b<_d;_b++){event=_c[_b];_a.push((function(){_e=event;keys=_e[0];callback=_e[1];if(!(keys.push)){keys=[keys];} +if($.inArray(e.keyCode,keys)>-1){return callback(e);}}).call(this));} +return _a;};$.MultiSelect.Selection=function Selection(element){this.input=$(element)[0];return this;};$.MultiSelect.Selection.prototype.get_caret=function get_caret(){var r;if(document.selection){r=document.selection.createRange().duplicate();r.moveEnd('character',this.input.value.length);if(r.text===''){return[this.input.value.length,this.input.value.length];}else{return[this.input.value.lastIndexOf(r.text),this.input.value.lastIndexOf(r.text)];}}else{return[this.input.selectionStart,this.input.selectionEnd];}};$.MultiSelect.Selection.prototype.set_caret=function set_caret(begin,end){end=(typeof end!=="undefined"&&end!==null)?end:begin;this.input.selectionStart=begin;this.input.selectionEnd=end;return this.input.selectionEnd;};$.MultiSelect.Selection.prototype.set_caret_at_end=function set_caret_at_end(){return this.set_caret(this.input.value.length);};$.MultiSelect.ResizableInput=function ResizableInput(element){this.input=$(element);this.create_measurer();this.input.keypress((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.set_width,this,[])));this.input.keyup((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.set_width,this,[])));this.input.change((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.set_width,this,[])));return this;};$.MultiSelect.ResizableInput.prototype.create_measurer=function create_measurer(){var measurer;if($("#__jquery_multiselect_measurer")[0]===undefined){measurer=$(document.createElement("div"));measurer.attr("id","__jquery_multiselect_measurer");measurer.css({position:"absolute",left:"-1000px",top:"-1000px"});$(document.body).append(measurer);} +this.measurer=$("#__jquery_multiselect_measurer:first");return this.measurer.css({fontSize:this.input.css('font-size'),fontFamily:this.input.css('font-family')});};$.MultiSelect.ResizableInput.prototype.calculate_width=function calculate_width(){this.measurer.html(this.input.val().entitizeHTML()+'MM');return this.measurer.innerWidth();};$.MultiSelect.ResizableInput.prototype.set_width=function set_width(){return this.input.css("width",this.calculate_width()+"px");};$.MultiSelect.AutoComplete=function AutoComplete(multiselect,completions){this.multiselect=multiselect;this.input=this.multiselect.input;this.completions=this.parse_completions(completions);this.matches=[];this.create_elements();this.bind_events();return this;};$.MultiSelect.AutoComplete.prototype.parse_completions=function parse_completions(completions){return $.map(completions,function(value){if(typeof value==="string"){return[[value,value]];}else if(value instanceof Array&&value.length===2){return[value];}else if(value.value&&value.caption){return[[value.caption,value.value]];}else if(console){return console.error("Invalid option "+(value));}});};$.MultiSelect.AutoComplete.prototype.create_elements=function create_elements(){this.container=$(document.createElement("div"));this.container.addClass("jquery-multiselect-autocomplete");this.container.css("width",this.multiselect.container.outerWidth());this.container.css("display","none");this.container.append(this.def);this.list=$(document.createElement("ul"));this.list.addClass("feed");this.container.append(this.list);return this.multiselect.container.after(this.container);};$.MultiSelect.AutoComplete.prototype.bind_events=function bind_events(){this.input.keypress((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.search,this,[])));this.input.keyup((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.search,this,[])));this.input.change((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.search,this,[])));this.multiselect.observer.bind(KEY.UP,(function(__this){var __func=function(e){e.preventDefault();return this.navigate_up();};return(function(){return __func.apply(__this,arguments);});})(this));return this.multiselect.observer.bind(KEY.DOWN,(function(__this){var __func=function(e){e.preventDefault();return this.navigate_down();};return(function(){return __func.apply(__this,arguments);});})(this));};$.MultiSelect.AutoComplete.prototype.search=function search(){var _a,_b,def,i,item,option,x;if(this.input.val().trim()===this.query){return null;} +this.query=this.input.val().trim();this.list.html("");this.current=0;if(this.query.present()){this.container.fadeIn("fast");this.matches=this.matching_completions(this.query);if(this.multiselect.options.enable_new_options){def=this.create_item("Add <em>"+this.query+"</em>");def.mouseover((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.select_index,this,[0])));} +_a=this.matches;for(i=0,_b=_a.length;i<_b;i++){option=_a[i];x=this.multiselect.options.enable_new_options?i+1:i;item=this.create_item(this.highlight(option[0],this.query));item.mouseover((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.select_index,this,[x])));} +if(this.multiselect.options.enable_new_options){this.matches.unshift([this.query,this.query]);} +return this.select_index(0);}else{this.matches=[];this.hide_complete_box();this.query=null;return this.query;}};$.MultiSelect.AutoComplete.prototype.hide_complete_box=function hide_complete_box(){return this.container.fadeOut("fast");};$.MultiSelect.AutoComplete.prototype.select_index=function select_index(index){var items;items=this.list.find("li");items.removeClass("auto-focus");items.filter(":eq("+(index)+")").addClass("auto-focus");this.current=index;return this.current;};$.MultiSelect.AutoComplete.prototype.navigate_down=function navigate_down(){var next;next=this.current+1;if(next>=this.matches.length){next=0;} +return this.select_index(next);};$.MultiSelect.AutoComplete.prototype.navigate_up=function navigate_up(){var next;next=this.current-1;if(next<0){next=this.matches.length-1;} +return this.select_index(next);};$.MultiSelect.AutoComplete.prototype.create_item=function create_item(text,highlight){var item;item=$(document.createElement("li"));item.click((function(__this){var __func=function(){this.multiselect.add_and_reset();this.search();return this.input.focus();};return(function(){return __func.apply(__this,arguments);});})(this));item.html(text);this.list.append(item);return item;};$.MultiSelect.AutoComplete.prototype.val=function val(){return this.matches[this.current];};$.MultiSelect.AutoComplete.prototype.highlight=function highlight(text,highlight){var _a,_b,char,current,highlighted,i,reg;if(this.multiselect.options.complex_search){highlighted="";current=0;_a=text;for(i=0,_b=_a.length;i<_b;i++){char=_a[i];char=text.charAt(i);if(current<highlight.length&&char.toLowerCase()===highlight.charAt(current).toLowerCase()){highlighted+="<em>"+(char)+"</em>";current++;}else{highlighted+=char;}} +return highlighted;}else{reg="("+(RegExp.escape(highlight))+")";return text.replace(new RegExp(reg,"gi"),'<em>$1</em>');}};$.MultiSelect.AutoComplete.prototype.matching_completions=function matching_completions(text){var _a,_b,char,count,i,reg;if(this.multiselect.options.complex_search){reg="";_a=text;for(i=0,_b=_a.length;i<_b;i++){char=_a[i];char=text.charAt(i);reg+=RegExp.escape(char)+".*";} +reg=new RegExp(reg,"i");}else{reg=new RegExp(RegExp.escape(text),"i");} +count=0;return $.grep(this.completions,(function(__this){var __func=function(c){if(count>=this.multiselect.options.max_complete_results){return false;} +if($.inArray(c[1],this.multiselect.values_real())>-1){return false;} +if(c[0].match(reg)){count++;return true;}else{return false;}};return(function(){return __func.apply(__this,arguments);});})(this));};$.fn.multiselect=function multiselect(options){options=(typeof options!=="undefined"&&options!==null)?options:{};return $(this).each(function(){var _a,_b,_c,completions,input,option,select_options;if(this.tagName.toLowerCase()==="select"){input=$(document.createElement("input"));input.attr("type","text");input.attr("name",this.name);input.attr("id",this.id);completions=[];_b=this.options;for(_a=0,_c=_b.length;_a<_c;_a++){option=_b[_a];completions.push([option.innerHTML,option.value]);} +select_options={completions:completions,enable_new_options:false};$.extend(select_options,options);$(this).replaceWith(input);return new $.MultiSelect(input,select_options);}else if(this.tagName.toLowerCase()==="input"&&this.type==="text"){return new $.MultiSelect(this,options);}});};return $.fn.multiselect;})(jQuery);$.extend(String.prototype,{trim:function trim(){return this.replace(/^[\r\n\s]/g,'').replace(/[\r\n\s]$/g,'');},entitizeHTML:function entitizeHTML(){return this.replace(/</g,'&lt;').replace(/>/g,'&gt;');},unentitizeHTML:function unentitizeHTML(){return this.replace(/&lt;/g,'<').replace(/&gt;/g,'>');},blank:function blank(){return this.trim().length===0;},present:function present(){return!this.blank();}});RegExp.escape=function escape(str){return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g,'\\$1');}; \ No newline at end of file
wilkerlucio/jquery-multiselect
4ad746d452ece641cfade4ff57b67fbc9145fd30
fixed complex search for IE
diff --git a/js/jquery.multiselect.js b/js/jquery.multiselect.js index e175963..093b046 100644 --- a/js/jquery.multiselect.js +++ b/js/jquery.multiselect.js @@ -1,597 +1,599 @@ // Copyright (c) 2010 Wilker Lúcio // // 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. (function($) { var KEY; KEY = { BACKSPACE: 8, TAB: 9, RETURN: 13, ESCAPE: 27, SPACE: 32, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, COLON: 188, DOT: 190 }; $.MultiSelect = function MultiSelect(element, options) { this.options = { separator: ",", completions: [], max_complete_results: 5, enable_new_options: true, complex_search: true }; $.extend(this.options, options || {}); this.values = []; this.input = $(element); this.initialize_elements(); this.initialize_events(); this.parse_value(); return this; }; $.MultiSelect.prototype.initialize_elements = function initialize_elements() { // hidden input to hold real value this.hidden = $(document.createElement("input")); this.hidden.attr("name", this.input.attr("name")); this.hidden.attr("type", "hidden"); this.input.removeAttr("name"); this.container = $(document.createElement("div")); this.container.addClass("jquery-multiselect"); this.input_wrapper = $(document.createElement("a")); this.input_wrapper.addClass("bit-input"); this.input.replaceWith(this.container); this.container.append(this.input_wrapper); this.input_wrapper.append(this.input); return this.container.before(this.hidden); }; $.MultiSelect.prototype.initialize_events = function initialize_events() { // create helpers this.selection = new $.MultiSelect.Selection(this.input); this.resizable = new $.MultiSelect.ResizableInput(this.input); this.observer = new $.MultiSelect.InputObserver(this.input); this.autocomplete = new $.MultiSelect.AutoComplete(this, this.options.completions); // prevent container click to put carret at end this.input.click((function(__this) { var __func = function(e) { return e.stopPropagation(); }; return (function() { return __func.apply(__this, arguments); }); })(this)); // create element when place separator or paste this.input.keyup((function(__this) { var __func = function() { return this.parse_value(1); }; return (function() { return __func.apply(__this, arguments); }); })(this)); // focus input and set carret at and this.container.click((function(__this) { var __func = function() { this.input.focus(); return this.selection.set_caret_at_end(); }; return (function() { return __func.apply(__this, arguments); }); })(this)); // add element on press TAB or RETURN this.observer.bind([KEY.TAB, KEY.RETURN], (function(__this) { var __func = function(e) { if (this.autocomplete.val()) { e.preventDefault(); return this.add_and_reset(); } }; return (function() { return __func.apply(__this, arguments); }); })(this)); // remove last item this.observer.bind([KEY.BACKSPACE], (function(__this) { var __func = function(e) { var caret; if (this.values.length <= 0) { return null; } caret = this.selection.get_caret(); if (caret[0] === 0 && caret[1] === 0) { e.preventDefault(); return this.remove(this.values[this.values.length - 1]); } }; return (function() { return __func.apply(__this, arguments); }); })(this)); // hide complete box this.input.blur((function(__this) { var __func = function() { return setTimeout((function(__this) { var __func = function() { return this.autocomplete.hide_complete_box(); }; return (function() { return __func.apply(__this, arguments); }); })(this), 200); }; return (function() { return __func.apply(__this, arguments); }); })(this)); return this.observer.bind([KEY.ESCAPE], (function(__this) { var __func = function(e) { return this.autocomplete.hide_complete_box(); }; return (function() { return __func.apply(__this, arguments); }); })(this)); }; $.MultiSelect.prototype.values_real = function values_real() { return $.map(this.values, function(v) { return v[1]; }); }; $.MultiSelect.prototype.parse_value = function parse_value(min) { var _a, _b, _c, value, values; min = (typeof min !== "undefined" && min !== null) ? min : 0; values = this.input.val().split(this.options.separator); if (values.length > min) { _b = values; for (_a = 0, _c = _b.length; _a < _c; _a++) { value = _b[_a]; if (value.present()) { this.add([value, value]); } } this.input.val(""); return this.autocomplete.search(); } }; $.MultiSelect.prototype.add_and_reset = function add_and_reset() { if (this.autocomplete.val()) { this.add(this.autocomplete.val()); this.input.val(""); return this.autocomplete.search(); } }; // add new element $.MultiSelect.prototype.add = function add(value) { var a, close; if ($.inArray(value[1], this.values_real()) > -1) { return null; } if (value[0].blank()) { return null; } value[1] = value[1].trim(); this.values.push(value); a = $(document.createElement("a")); a.addClass("bit bit-box"); a.mouseover(function() { return $(this).addClass("bit-hover"); }); a.mouseout(function() { return $(this).removeClass("bit-hover"); }); a.data("value", value); a.html(value[0].entitizeHTML()); close = $(document.createElement("a")); close.addClass("closebutton"); close.click((function(__this) { var __func = function() { return this.remove(a.data("value")); }; return (function() { return __func.apply(__this, arguments); }); })(this)); a.append(close); this.input_wrapper.before(a); return this.refresh_hidden(); }; $.MultiSelect.prototype.remove = function remove(value) { this.values = $.grep(this.values, function(v) { return v[1] !== value[1]; }); this.container.find("a.bit-box").each(function() { if ($(this).data("value")[1] === value[1]) { return $(this).remove(); } }); return this.refresh_hidden(); }; $.MultiSelect.prototype.refresh_hidden = function refresh_hidden() { return this.hidden.val(this.values_real().join(this.options.separator)); }; // Input Observer Helper $.MultiSelect.InputObserver = function InputObserver(element) { this.input = $(element); this.input.keydown((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.handle_keydown, this, []))); this.events = []; return this; }; $.MultiSelect.InputObserver.prototype.bind = function bind(key, callback) { return this.events.push([key, callback]); }; $.MultiSelect.InputObserver.prototype.handle_keydown = function handle_keydown(e) { var _a, _b, _c, _d, _e, callback, event, keys; _a = []; _c = this.events; for (_b = 0, _d = _c.length; _b < _d; _b++) { event = _c[_b]; _a.push((function() { _e = event; keys = _e[0]; callback = _e[1]; if (!(keys.push)) { keys = [keys]; } if ($.inArray(e.keyCode, keys) > -1) { return callback(e); } }).call(this)); } return _a; }; // Selection Helper $.MultiSelect.Selection = function Selection(element) { this.input = $(element)[0]; return this; }; $.MultiSelect.Selection.prototype.get_caret = function get_caret() { var r; // For IE if (document.selection) { r = document.selection.createRange().duplicate(); r.moveEnd('character', this.input.value.length); if (r.text === '') { return [this.input.value.length, this.input.value.length]; } else { return [this.input.value.lastIndexOf(r.text), this.input.value.lastIndexOf(r.text)]; // Others } } else { return [this.input.selectionStart, this.input.selectionEnd]; } }; $.MultiSelect.Selection.prototype.set_caret = function set_caret(begin, end) { end = (typeof end !== "undefined" && end !== null) ? end : begin; this.input.selectionStart = begin; this.input.selectionEnd = end; return this.input.selectionEnd; }; $.MultiSelect.Selection.prototype.set_caret_at_end = function set_caret_at_end() { return this.set_caret(this.input.value.length); }; // Resizable Input Helper $.MultiSelect.ResizableInput = function ResizableInput(element) { this.input = $(element); this.create_measurer(); this.input.keypress((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.set_width, this, []))); this.input.keyup((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.set_width, this, []))); this.input.change((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.set_width, this, []))); return this; }; $.MultiSelect.ResizableInput.prototype.create_measurer = function create_measurer() { var measurer; if ($("#__jquery_multiselect_measurer")[0] === undefined) { measurer = $(document.createElement("div")); measurer.attr("id", "__jquery_multiselect_measurer"); measurer.css({ position: "absolute", left: "-1000px", top: "-1000px" }); $(document.body).append(measurer); } this.measurer = $("#__jquery_multiselect_measurer:first"); return this.measurer.css({ fontSize: this.input.css('font-size'), fontFamily: this.input.css('font-family') }); }; $.MultiSelect.ResizableInput.prototype.calculate_width = function calculate_width() { this.measurer.html(this.input.val().entitizeHTML() + 'MM'); return this.measurer.innerWidth(); }; $.MultiSelect.ResizableInput.prototype.set_width = function set_width() { return this.input.css("width", this.calculate_width() + "px"); }; // AutoComplete Helper $.MultiSelect.AutoComplete = function AutoComplete(multiselect, completions) { this.multiselect = multiselect; this.input = this.multiselect.input; this.completions = this.parse_completions(completions); this.matches = []; this.create_elements(); this.bind_events(); return this; }; $.MultiSelect.AutoComplete.prototype.parse_completions = function parse_completions(completions) { return $.map(completions, function(value) { if (typeof value === "string") { return [[value, value]]; } else if (value instanceof Array && value.length === 2) { return [value]; } else if (value.value && value.caption) { return [[value.caption, value.value]]; } else if (console) { return console.error("Invalid option " + (value)); } }); }; $.MultiSelect.AutoComplete.prototype.create_elements = function create_elements() { this.container = $(document.createElement("div")); this.container.addClass("jquery-multiselect-autocomplete"); this.container.css("width", this.multiselect.container.outerWidth()); this.container.css("display", "none"); this.container.append(this.def); this.list = $(document.createElement("ul")); this.list.addClass("feed"); this.container.append(this.list); return this.multiselect.container.after(this.container); }; $.MultiSelect.AutoComplete.prototype.bind_events = function bind_events() { this.input.keypress((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.search, this, []))); this.input.keyup((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.search, this, []))); this.input.change((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.search, this, []))); this.multiselect.observer.bind(KEY.UP, (function(__this) { var __func = function(e) { e.preventDefault(); return this.navigate_up(); }; return (function() { return __func.apply(__this, arguments); }); })(this)); return this.multiselect.observer.bind(KEY.DOWN, (function(__this) { var __func = function(e) { e.preventDefault(); return this.navigate_down(); }; return (function() { return __func.apply(__this, arguments); }); })(this)); }; $.MultiSelect.AutoComplete.prototype.search = function search() { var _a, _b, def, i, item, option, x; if (this.input.val().trim() === this.query) { return null; } // dont do operation if query is same this.query = this.input.val().trim(); this.list.html(""); // clear list this.current = 0; if (this.query.present()) { this.container.fadeIn("fast"); this.matches = this.matching_completions(this.query); if (this.multiselect.options.enable_new_options) { def = this.create_item("Add <em>" + this.query + "</em>"); def.mouseover((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.select_index, this, [0]))); } _a = this.matches; for (i = 0, _b = _a.length; i < _b; i++) { option = _a[i]; x = this.multiselect.options.enable_new_options ? i + 1 : i; item = this.create_item(this.highlight(option[0], this.query)); item.mouseover((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.select_index, this, [x]))); } if (this.multiselect.options.enable_new_options) { this.matches.unshift([this.query, this.query]); } return this.select_index(0); } else { this.matches = []; this.hide_complete_box(); this.query = null; return this.query; } }; $.MultiSelect.AutoComplete.prototype.hide_complete_box = function hide_complete_box() { return this.container.fadeOut("fast"); }; $.MultiSelect.AutoComplete.prototype.select_index = function select_index(index) { var items; items = this.list.find("li"); items.removeClass("auto-focus"); items.filter(":eq(" + (index) + ")").addClass("auto-focus"); this.current = index; return this.current; }; $.MultiSelect.AutoComplete.prototype.navigate_down = function navigate_down() { var next; next = this.current + 1; if (next >= this.matches.length) { next = 0; } return this.select_index(next); }; $.MultiSelect.AutoComplete.prototype.navigate_up = function navigate_up() { var next; next = this.current - 1; if (next < 0) { next = this.matches.length - 1; } return this.select_index(next); }; $.MultiSelect.AutoComplete.prototype.create_item = function create_item(text, highlight) { var item; item = $(document.createElement("li")); item.click((function(__this) { var __func = function() { this.multiselect.add_and_reset(); this.search(); return this.input.focus(); }; return (function() { return __func.apply(__this, arguments); }); })(this)); item.html(text); this.list.append(item); return item; }; $.MultiSelect.AutoComplete.prototype.val = function val() { return this.matches[this.current]; }; $.MultiSelect.AutoComplete.prototype.highlight = function highlight(text, highlight) { - var _a, _b, _c, char, current, highlighted, reg; + var _a, _b, char, current, highlighted, i, reg; if (this.multiselect.options.complex_search) { highlighted = ""; current = 0; - _b = text; - for (_a = 0, _c = _b.length; _a < _c; _a++) { - char = _b[_a]; - if (current < highlight.length && char.toLowerCase() === highlight[current].toLowerCase()) { + _a = text; + for (i = 0, _b = _a.length; i < _b; i++) { + char = _a[i]; + char = text.charAt(i); + if (current < highlight.length && char.toLowerCase() === highlight.charAt(current).toLowerCase()) { highlighted += "<em>" + (char) + "</em>"; current++; } else { highlighted += char; } } return highlighted; } else { reg = "(" + (RegExp.escape(highlight)) + ")"; return text.replace(new RegExp(reg, "gi"), '<em>$1</em>'); } }; $.MultiSelect.AutoComplete.prototype.matching_completions = function matching_completions(text) { - var _a, _b, _c, char, count, reg; + var _a, _b, char, count, i, reg; if (this.multiselect.options.complex_search) { reg = ""; - _b = text; - for (_a = 0, _c = _b.length; _a < _c; _a++) { - char = _b[_a]; + _a = text; + for (i = 0, _b = _a.length; i < _b; i++) { + char = _a[i]; + char = text.charAt(i); reg += RegExp.escape(char) + ".*"; } reg = new RegExp(reg, "i"); } else { reg = new RegExp(RegExp.escape(text), "i"); } count = 0; return $.grep(this.completions, (function(__this) { var __func = function(c) { if (count >= this.multiselect.options.max_complete_results) { return false; } if ($.inArray(c[1], this.multiselect.values_real()) > -1) { return false; } if (c[0].match(reg)) { count++; return true; } else { return false; } }; return (function() { return __func.apply(__this, arguments); }); })(this)); }; // Hook jQuery extension $.fn.multiselect = function multiselect(options) { options = (typeof options !== "undefined" && options !== null) ? options : {}; return $(this).each(function() { var _a, _b, _c, completions, input, option, select_options; if (this.tagName.toLowerCase() === "select") { input = $(document.createElement("input")); input.attr("type", "text"); input.attr("name", this.name); input.attr("id", this.id); completions = []; _b = this.options; for (_a = 0, _c = _b.length; _a < _c; _a++) { option = _b[_a]; completions.push([option.innerHTML, option.value]); } select_options = { completions: completions, enable_new_options: false }; $.extend(select_options, options); $(this).replaceWith(input); return new $.MultiSelect(input, select_options); } else if (this.tagName.toLowerCase() === "input" && this.type === "text") { return new $.MultiSelect(this, options); } }); }; return $.fn.multiselect; })(jQuery); $.extend(String.prototype, { trim: function trim() { return this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, ''); }, entitizeHTML: function entitizeHTML() { return this.replace(/</g, '&lt;').replace(/>/g, '&gt;'); }, unentitizeHTML: function unentitizeHTML() { return this.replace(/&lt;/g, '<').replace(/&gt;/g, '>'); }, blank: function blank() { return this.trim().length === 0; }, present: function present() { return !this.blank(); } }); RegExp.escape = function escape(str) { return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); }; \ No newline at end of file diff --git a/src/jquery.multiselect.coffee b/src/jquery.multiselect.coffee index c688a9f..4768460 100644 --- a/src/jquery.multiselect.coffee +++ b/src/jquery.multiselect.coffee @@ -1,416 +1,418 @@ # Copyright (c) 2010 Wilker Lúcio # # 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. (($) -> KEY: { BACKSPACE: 8 TAB: 9 RETURN: 13 ESCAPE: 27 SPACE: 32 LEFT: 37 UP: 38 RIGHT: 39 DOWN: 40 COLON: 188 DOT: 190 } class $.MultiSelect constructor: (element, options) -> @options: { separator: "," completions: [] max_complete_results: 5 enable_new_options: true complex_search: true } $.extend(@options, options || {}) @values: [] @input: $(element) @initialize_elements() @initialize_events() @parse_value() initialize_elements: -> # hidden input to hold real value @hidden: $(document.createElement("input")) @hidden.attr("name", @input.attr("name")) @hidden.attr("type", "hidden") @input.removeAttr("name") @container: $(document.createElement("div")) @container.addClass("jquery-multiselect") @input_wrapper: $(document.createElement("a")) @input_wrapper.addClass("bit-input") @input.replaceWith(@container) @container.append(@input_wrapper) @input_wrapper.append(@input) @container.before(@hidden) initialize_events: -> # create helpers @selection: new $.MultiSelect.Selection(@input) @resizable: new $.MultiSelect.ResizableInput(@input) @observer: new $.MultiSelect.InputObserver(@input) @autocomplete: new $.MultiSelect.AutoComplete(this, @options.completions) # prevent container click to put carret at end @input.click (e) => e.stopPropagation() # create element when place separator or paste @input.keyup => @parse_value(1) # focus input and set carret at and @container.click => @input.focus() @selection.set_caret_at_end() # add element on press TAB or RETURN @observer.bind [KEY.TAB, KEY.RETURN], (e) => if @autocomplete.val() e.preventDefault() @add_and_reset() # remove last item @observer.bind [KEY.BACKSPACE], (e) => return if @values.length <= 0 caret = @selection.get_caret() if caret[0] == 0 and caret[1] == 0 e.preventDefault() @remove(@values[@values.length - 1]) # hide complete box @input.blur => setTimeout(=> @autocomplete.hide_complete_box() 200) @observer.bind [KEY.ESCAPE], (e) => @autocomplete.hide_complete_box() values_real: -> $.map @values, (v) -> v[1] parse_value: (min) -> min ?= 0 values: @input.val().split(@options.separator) if values.length > min for value in values @add [value, value] if value.present() @input.val("") @autocomplete.search() add_and_reset: -> if @autocomplete.val() @add(@autocomplete.val()) @input.val("") @autocomplete.search() # add new element add: (value) -> return if $.inArray(value[1], @values_real()) > -1 return if value[0].blank() value[1] = value[1].trim() @values.push(value) a: $(document.createElement("a")) a.addClass("bit bit-box") a.mouseover -> $(this).addClass("bit-hover") a.mouseout -> $(this).removeClass("bit-hover") a.data("value", value) a.html(value[0].entitizeHTML()) close: $(document.createElement("a")) close.addClass("closebutton") close.click => @remove(a.data("value")) a.append(close) @input_wrapper.before(a) @refresh_hidden() remove: (value) -> @values: $.grep @values, (v) -> v[1] != value[1] @container.find("a.bit-box").each -> $(this).remove() if $(this).data("value")[1] == value[1] @refresh_hidden() refresh_hidden: -> @hidden.val(@values_real().join(@options.separator)) # Input Observer Helper class $.MultiSelect.InputObserver constructor: (element) -> @input: $(element) @input.keydown(@handle_keydown <- this) @events: [] bind: (key, callback) -> @events.push([key, callback]) handle_keydown: (e) -> for event in @events [keys, callback]: event keys: [keys] unless keys.push callback(e) if $.inArray(e.keyCode, keys) > -1 # Selection Helper class $.MultiSelect.Selection constructor: (element) -> @input: $(element)[0] get_caret: -> # For IE if document.selection r: document.selection.createRange().duplicate() r.moveEnd('character', @input.value.length) if r.text == '' [@input.value.length, @input.value.length] else [@input.value.lastIndexOf(r.text), @input.value.lastIndexOf(r.text)] # Others else [@input.selectionStart, @input.selectionEnd] set_caret: (begin, end) -> end ?= begin @input.selectionStart: begin @input.selectionEnd: end set_caret_at_end: -> @set_caret(@input.value.length) # Resizable Input Helper class $.MultiSelect.ResizableInput constructor: (element) -> @input: $(element) @create_measurer() @input.keypress(@set_width <- this) @input.keyup(@set_width <- this) @input.change(@set_width <- this) create_measurer: -> if $("#__jquery_multiselect_measurer")[0] == undefined measurer: $(document.createElement("div")) measurer.attr("id", "__jquery_multiselect_measurer") measurer.css { position: "absolute" left: "-1000px" top: "-1000px" } $(document.body).append(measurer) @measurer: $("#__jquery_multiselect_measurer:first") @measurer.css { fontSize: @input.css('font-size') fontFamily: @input.css('font-family') } calculate_width: -> @measurer.html(@input.val().entitizeHTML() + 'MM') @measurer.innerWidth() set_width: -> @input.css("width", @calculate_width() + "px") # AutoComplete Helper class $.MultiSelect.AutoComplete constructor: (multiselect, completions) -> @multiselect: multiselect @input: @multiselect.input @completions: @parse_completions(completions) @matches: [] @create_elements() @bind_events() parse_completions: (completions) -> $.map completions, (value) -> if typeof value == "string" [[value, value]] else if value instanceof Array and value.length == 2 [value] else if value.value and value.caption [[value.caption, value.value]] else console.error "Invalid option ${value}" if console create_elements: -> @container: $(document.createElement("div")) @container.addClass("jquery-multiselect-autocomplete") @container.css("width", @multiselect.container.outerWidth()) @container.css("display", "none") @container.append(@def) @list: $(document.createElement("ul")) @list.addClass("feed") @container.append(@list) @multiselect.container.after(@container) bind_events: -> @input.keypress(@search <- this) @input.keyup(@search <- this) @input.change(@search <- this) @multiselect.observer.bind KEY.UP, (e) => e.preventDefault(); @navigate_up() @multiselect.observer.bind KEY.DOWN, (e) => e.preventDefault(); @navigate_down() search: -> return if @input.val().trim() == @query # dont do operation if query is same @query: @input.val().trim() @list.html("") # clear list @current: 0 if @query.present() @container.fadeIn("fast") @matches: @matching_completions(@query) if @multiselect.options.enable_new_options def: @create_item("Add <em>" + @query + "</em>") def.mouseover(@select_index <- this, 0) for option, i in @matches x: if @multiselect.options.enable_new_options then i + 1 else i item: @create_item(@highlight(option[0], @query)) item.mouseover(@select_index <- this, x) @matches.unshift([@query, @query]) if @multiselect.options.enable_new_options @select_index(0) else @matches: [] @hide_complete_box() @query: null hide_complete_box: -> @container.fadeOut("fast") select_index: (index) -> items: @list.find("li") items.removeClass("auto-focus") items.filter(":eq(${index})").addClass("auto-focus") @current: index navigate_down: -> next: @current + 1 next: 0 if next >= @matches.length @select_index(next) navigate_up: -> next: @current - 1 next: @matches.length - 1 if next < 0 @select_index(next) create_item: (text, highlight) -> item: $(document.createElement("li")) item.click => @multiselect.add_and_reset() @search() @input.focus() item.html(text) @list.append(item) item val: -> @matches[@current] highlight: (text, highlight) -> if @multiselect.options.complex_search highlighted: "" current: 0 - for char in text - if current < highlight.length and char.toLowerCase() == highlight[current].toLowerCase() + for char, i in text + char: text.charAt(i) + if current < highlight.length and char.toLowerCase() == highlight.charAt(current).toLowerCase() highlighted += "<em>${char}</em>" current++ else highlighted += char highlighted else reg: "(${RegExp.escape(highlight)})" text.replace(new RegExp(reg, "gi"), '<em>$1</em>') matching_completions: (text) -> if @multiselect.options.complex_search reg: "" - for char in text + for char, i in text + char: text.charAt(i) reg += RegExp.escape(char) + ".*" reg: new RegExp(reg, "i") else reg: new RegExp(RegExp.escape(text), "i") count: 0 $.grep @completions, (c) => return false if count >= @multiselect.options.max_complete_results return false if $.inArray(c[1], @multiselect.values_real()) > -1 if c[0].match(reg) count++ true else false # Hook jQuery extension $.fn.multiselect: (options) -> options ?= {} $(this).each -> if this.tagName.toLowerCase() == "select" input: $(document.createElement("input")) input.attr("type", "text") input.attr("name", this.name) input.attr("id", this.id) completions: [] for option in this.options completions.push([option.innerHTML, option.value]) select_options: { completions: completions enable_new_options: false } $.extend(select_options, options) $(this).replaceWith(input) new $.MultiSelect(input, select_options) else if this.tagName.toLowerCase() == "input" and this.type == "text" new $.MultiSelect(this, options) )(jQuery) $.extend String.prototype, { trim: -> this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, '') entitizeHTML: -> this.replace(/</g,'&lt;').replace(/>/g,'&gt;') unentitizeHTML: -> this.replace(/&lt;/g,'<').replace(/&gt;/g,'>') blank: -> this.trim().length == 0 present: -> not @blank() }; RegExp.escape: (str) -> String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
wilkerlucio/jquery-multiselect
39dbff7426be1f03cf36653287e0fe0ac30e1d7b
release 0.1.6
diff --git a/VERSION b/VERSION index def9a01..a192233 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.1.5 \ No newline at end of file +0.1.6 \ No newline at end of file diff --git a/dist/jquery.multiselect.0.1.6.min.js b/dist/jquery.multiselect.0.1.6.min.js new file mode 100644 index 0000000..3c655d1 --- /dev/null +++ b/dist/jquery.multiselect.0.1.6.min.js @@ -0,0 +1,36 @@ +/** + * Copyright (c) 2010 Wilker Lúcio + * + * 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. + */ + +(function($){var KEY;KEY={BACKSPACE:8,TAB:9,RETURN:13,ESCAPE:27,SPACE:32,LEFT:37,UP:38,RIGHT:39,DOWN:40,COLON:188,DOT:190};$.MultiSelect=function MultiSelect(element,options){this.options={separator:",",completions:[],max_complete_results:5,enable_new_options:true,complex_search:true};$.extend(this.options,options||{});this.values=[];this.input=$(element);this.initialize_elements();this.initialize_events();this.parse_value();return this;};$.MultiSelect.prototype.initialize_elements=function initialize_elements(){this.hidden=$(document.createElement("input"));this.hidden.attr("name",this.input.attr("name"));this.hidden.attr("type","hidden");this.input.removeAttr("name");this.container=$(document.createElement("div"));this.container.addClass("jquery-multiselect");this.input_wrapper=$(document.createElement("a"));this.input_wrapper.addClass("bit-input");this.input.replaceWith(this.container);this.container.append(this.input_wrapper);this.input_wrapper.append(this.input);return this.container.before(this.hidden);};$.MultiSelect.prototype.initialize_events=function initialize_events(){this.selection=new $.MultiSelect.Selection(this.input);this.resizable=new $.MultiSelect.ResizableInput(this.input);this.observer=new $.MultiSelect.InputObserver(this.input);this.autocomplete=new $.MultiSelect.AutoComplete(this,this.options.completions);this.input.click((function(__this){var __func=function(e){return e.stopPropagation();};return(function(){return __func.apply(__this,arguments);});})(this));this.input.keyup((function(__this){var __func=function(){return this.parse_value(1);};return(function(){return __func.apply(__this,arguments);});})(this));this.container.click((function(__this){var __func=function(){this.input.focus();return this.selection.set_caret_at_end();};return(function(){return __func.apply(__this,arguments);});})(this));this.observer.bind([KEY.TAB,KEY.RETURN],(function(__this){var __func=function(e){if(this.autocomplete.val()){e.preventDefault();return this.add_and_reset();}};return(function(){return __func.apply(__this,arguments);});})(this));this.observer.bind([KEY.BACKSPACE],(function(__this){var __func=function(e){var caret;if(this.values.length<=0){return null;} +caret=this.selection.get_caret();if(caret[0]===0&&caret[1]===0){e.preventDefault();return this.remove(this.values[this.values.length-1]);}};return(function(){return __func.apply(__this,arguments);});})(this));this.input.blur((function(__this){var __func=function(){return setTimeout((function(__this){var __func=function(){return this.autocomplete.hide_complete_box();};return(function(){return __func.apply(__this,arguments);});})(this),200);};return(function(){return __func.apply(__this,arguments);});})(this));return this.observer.bind([KEY.ESCAPE],(function(__this){var __func=function(e){return this.autocomplete.hide_complete_box();};return(function(){return __func.apply(__this,arguments);});})(this));};$.MultiSelect.prototype.values_real=function values_real(){return $.map(this.values,function(v){return v[1];});};$.MultiSelect.prototype.parse_value=function parse_value(min){var _a,_b,_c,value,values;min=(typeof min!=="undefined"&&min!==null)?min:0;values=this.input.val().split(this.options.separator);if(values.length>min){_b=values;for(_a=0,_c=_b.length;_a<_c;_a++){value=_b[_a];if(value.present()){this.add([value,value]);}} +this.input.val("");return this.autocomplete.search();}};$.MultiSelect.prototype.add_and_reset=function add_and_reset(){if(this.autocomplete.val()){this.add(this.autocomplete.val());this.input.val("");return this.autocomplete.search();}};$.MultiSelect.prototype.add=function add(value){var a,close;if($.inArray(value[1],this.values_real())>-1){return null;} +if(value[0].blank()){return null;} +value[1]=value[1].trim();this.values.push(value);a=$(document.createElement("a"));a.addClass("bit bit-box");a.mouseover(function(){return $(this).addClass("bit-hover");});a.mouseout(function(){return $(this).removeClass("bit-hover");});a.data("value",value);a.html(value[0].entitizeHTML());close=$(document.createElement("a"));close.addClass("closebutton");close.click((function(__this){var __func=function(){return this.remove(a.data("value"));};return(function(){return __func.apply(__this,arguments);});})(this));a.append(close);this.input_wrapper.before(a);return this.refresh_hidden();};$.MultiSelect.prototype.remove=function remove(value){this.values=$.grep(this.values,function(v){return v[1]!==value[1];});this.container.find("a.bit-box").each(function(){if($(this).data("value")[1]===value[1]){return $(this).remove();}});return this.refresh_hidden();};$.MultiSelect.prototype.refresh_hidden=function refresh_hidden(){return this.hidden.val(this.values_real().join(this.options.separator));};$.MultiSelect.InputObserver=function InputObserver(element){this.input=$(element);this.input.keydown((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.handle_keydown,this,[])));this.events=[];return this;};$.MultiSelect.InputObserver.prototype.bind=function bind(key,callback){return this.events.push([key,callback]);};$.MultiSelect.InputObserver.prototype.handle_keydown=function handle_keydown(e){var _a,_b,_c,_d,_e,callback,event,keys;_a=[];_c=this.events;for(_b=0,_d=_c.length;_b<_d;_b++){event=_c[_b];_a.push((function(){_e=event;keys=_e[0];callback=_e[1];if(!(keys.push)){keys=[keys];} +if($.inArray(e.keyCode,keys)>-1){return callback(e);}}).call(this));} +return _a;};$.MultiSelect.Selection=function Selection(element){this.input=$(element)[0];return this;};$.MultiSelect.Selection.prototype.get_caret=function get_caret(){var r;if(document.selection){r=document.selection.createRange().duplicate();r.moveEnd('character',this.input.value.length);if(r.text===''){return[this.input.value.length,this.input.value.length];}else{return[this.input.value.lastIndexOf(r.text),this.input.value.lastIndexOf(r.text)];}}else{return[this.input.selectionStart,this.input.selectionEnd];}};$.MultiSelect.Selection.prototype.set_caret=function set_caret(begin,end){end=(typeof end!=="undefined"&&end!==null)?end:begin;this.input.selectionStart=begin;this.input.selectionEnd=end;return this.input.selectionEnd;};$.MultiSelect.Selection.prototype.set_caret_at_end=function set_caret_at_end(){return this.set_caret(this.input.value.length);};$.MultiSelect.ResizableInput=function ResizableInput(element){this.input=$(element);this.create_measurer();this.input.keypress((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.set_width,this,[])));this.input.keyup((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.set_width,this,[])));this.input.change((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.set_width,this,[])));return this;};$.MultiSelect.ResizableInput.prototype.create_measurer=function create_measurer(){var measurer;if($("#__jquery_multiselect_measurer")[0]===undefined){measurer=$(document.createElement("div"));measurer.attr("id","__jquery_multiselect_measurer");measurer.css({position:"absolute",left:"-1000px",top:"-1000px"});$(document.body).append(measurer);} +this.measurer=$("#__jquery_multiselect_measurer:first");return this.measurer.css({fontSize:this.input.css('font-size'),fontFamily:this.input.css('font-family')});};$.MultiSelect.ResizableInput.prototype.calculate_width=function calculate_width(){this.measurer.html(this.input.val().entitizeHTML()+'MM');return this.measurer.innerWidth();};$.MultiSelect.ResizableInput.prototype.set_width=function set_width(){return this.input.css("width",this.calculate_width()+"px");};$.MultiSelect.AutoComplete=function AutoComplete(multiselect,completions){this.multiselect=multiselect;this.input=this.multiselect.input;this.completions=this.parse_completions(completions);this.matches=[];this.create_elements();this.bind_events();return this;};$.MultiSelect.AutoComplete.prototype.parse_completions=function parse_completions(completions){return $.map(completions,function(value){if(typeof value==="string"){return[[value,value]];}else if(value instanceof Array&&value.length===2){return[value];}else if(value.value&&value.caption){return[[value.caption,value.value]];}else if(console){return console.error("Invalid option "+(value));}});};$.MultiSelect.AutoComplete.prototype.create_elements=function create_elements(){this.container=$(document.createElement("div"));this.container.addClass("jquery-multiselect-autocomplete");this.container.css("width",this.multiselect.container.outerWidth());this.container.css("display","none");this.container.append(this.def);this.list=$(document.createElement("ul"));this.list.addClass("feed");this.container.append(this.list);return this.multiselect.container.after(this.container);};$.MultiSelect.AutoComplete.prototype.bind_events=function bind_events(){this.input.keypress((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.search,this,[])));this.input.keyup((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.search,this,[])));this.input.change((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.search,this,[])));this.multiselect.observer.bind(KEY.UP,(function(__this){var __func=function(e){e.preventDefault();return this.navigate_up();};return(function(){return __func.apply(__this,arguments);});})(this));return this.multiselect.observer.bind(KEY.DOWN,(function(__this){var __func=function(e){e.preventDefault();return this.navigate_down();};return(function(){return __func.apply(__this,arguments);});})(this));};$.MultiSelect.AutoComplete.prototype.search=function search(){var _a,_b,def,i,item,option,x;if(this.input.val().trim()===this.query){return null;} +this.query=this.input.val().trim();this.list.html("");this.current=0;if(this.query.present()){this.container.fadeIn("fast");this.matches=this.matching_completions(this.query);if(this.multiselect.options.enable_new_options){def=this.create_item("Add <em>"+this.query+"</em>");def.mouseover((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.select_index,this,[0])));} +_a=this.matches;for(i=0,_b=_a.length;i<_b;i++){option=_a[i];x=this.multiselect.options.enable_new_options?i+1:i;item=this.create_item(this.highlight(option[0],this.query));item.mouseover((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.select_index,this,[x])));} +if(this.multiselect.options.enable_new_options){this.matches.unshift([this.query,this.query]);} +return this.select_index(0);}else{this.matches=[];this.hide_complete_box();this.query=null;return this.query;}};$.MultiSelect.AutoComplete.prototype.hide_complete_box=function hide_complete_box(){return this.container.fadeOut("fast");};$.MultiSelect.AutoComplete.prototype.select_index=function select_index(index){var items;items=this.list.find("li");items.removeClass("auto-focus");items.filter(":eq("+(index)+")").addClass("auto-focus");this.current=index;return this.current;};$.MultiSelect.AutoComplete.prototype.navigate_down=function navigate_down(){var next;next=this.current+1;if(next>=this.matches.length){next=0;} +return this.select_index(next);};$.MultiSelect.AutoComplete.prototype.navigate_up=function navigate_up(){var next;next=this.current-1;if(next<0){next=this.matches.length-1;} +return this.select_index(next);};$.MultiSelect.AutoComplete.prototype.create_item=function create_item(text,highlight){var item;item=$(document.createElement("li"));item.click((function(__this){var __func=function(){this.multiselect.add_and_reset();this.search();return this.input.focus();};return(function(){return __func.apply(__this,arguments);});})(this));item.html(text);this.list.append(item);return item;};$.MultiSelect.AutoComplete.prototype.val=function val(){return this.matches[this.current];};$.MultiSelect.AutoComplete.prototype.highlight=function highlight(text,highlight){var _a,_b,_c,char,current,highlighted,reg;if(this.multiselect.options.complex_search){highlighted="";current=0;_b=text;for(_a=0,_c=_b.length;_a<_c;_a++){char=_b[_a];if(current<highlight.length&&char.toLowerCase()===highlight[current].toLowerCase()){highlighted+="<em>"+(char)+"</em>";current++;}else{highlighted+=char;}} +return highlighted;}else{reg="("+(RegExp.escape(highlight))+")";return text.replace(new RegExp(reg,"gi"),'<em>$1</em>');}};$.MultiSelect.AutoComplete.prototype.matching_completions=function matching_completions(text){var _a,_b,_c,char,count,reg;if(this.multiselect.options.complex_search){reg="";_b=text;for(_a=0,_c=_b.length;_a<_c;_a++){char=_b[_a];reg+=RegExp.escape(char)+".*";} +reg=new RegExp(reg,"i");}else{reg=new RegExp(RegExp.escape(text),"i");} +count=0;return $.grep(this.completions,(function(__this){var __func=function(c){if(count>=this.multiselect.options.max_complete_results){return false;} +if($.inArray(c[1],this.multiselect.values_real())>-1){return false;} +if(c[0].match(reg)){count++;return true;}else{return false;}};return(function(){return __func.apply(__this,arguments);});})(this));};$.fn.multiselect=function multiselect(options){options=(typeof options!=="undefined"&&options!==null)?options:{};return $(this).each(function(){var _a,_b,_c,completions,input,option,select_options;if(this.tagName.toLowerCase()==="select"){input=$(document.createElement("input"));input.attr("type","text");input.attr("name",this.name);input.attr("id",this.id);completions=[];_b=this.options;for(_a=0,_c=_b.length;_a<_c;_a++){option=_b[_a];completions.push([option.innerHTML,option.value]);} +select_options={completions:completions,enable_new_options:false};$.extend(select_options,options);$(this).replaceWith(input);return new $.MultiSelect(input,select_options);}else if(this.tagName.toLowerCase()==="input"&&this.type==="text"){return new $.MultiSelect(this,options);}});};return $.fn.multiselect;})(jQuery);$.extend(String.prototype,{trim:function trim(){return this.replace(/^[\r\n\s]/g,'').replace(/[\r\n\s]$/g,'');},entitizeHTML:function entitizeHTML(){return this.replace(/</g,'&lt;').replace(/>/g,'&gt;');},unentitizeHTML:function unentitizeHTML(){return this.replace(/&lt;/g,'<').replace(/&gt;/g,'>');},blank:function blank(){return this.trim().length===0;},present:function present(){return!this.blank();}});RegExp.escape=function escape(str){return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g,'\\$1');}; \ No newline at end of file
wilkerlucio/jquery-multiselect
722fc4e2f0faac91c947fea5ab38072483bc7c2b
added complex search
diff --git a/js/jquery.multiselect.js b/js/jquery.multiselect.js index cbb3c1a..e175963 100644 --- a/js/jquery.multiselect.js +++ b/js/jquery.multiselect.js @@ -1,570 +1,597 @@ // Copyright (c) 2010 Wilker Lúcio // // 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. (function($) { var KEY; KEY = { BACKSPACE: 8, TAB: 9, RETURN: 13, ESCAPE: 27, SPACE: 32, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, COLON: 188, DOT: 190 }; $.MultiSelect = function MultiSelect(element, options) { this.options = { separator: ",", completions: [], max_complete_results: 5, - enable_new_options: true + enable_new_options: true, + complex_search: true }; $.extend(this.options, options || {}); this.values = []; this.input = $(element); this.initialize_elements(); this.initialize_events(); this.parse_value(); return this; }; $.MultiSelect.prototype.initialize_elements = function initialize_elements() { // hidden input to hold real value this.hidden = $(document.createElement("input")); this.hidden.attr("name", this.input.attr("name")); this.hidden.attr("type", "hidden"); this.input.removeAttr("name"); this.container = $(document.createElement("div")); this.container.addClass("jquery-multiselect"); this.input_wrapper = $(document.createElement("a")); this.input_wrapper.addClass("bit-input"); this.input.replaceWith(this.container); this.container.append(this.input_wrapper); this.input_wrapper.append(this.input); return this.container.before(this.hidden); }; $.MultiSelect.prototype.initialize_events = function initialize_events() { // create helpers this.selection = new $.MultiSelect.Selection(this.input); this.resizable = new $.MultiSelect.ResizableInput(this.input); this.observer = new $.MultiSelect.InputObserver(this.input); this.autocomplete = new $.MultiSelect.AutoComplete(this, this.options.completions); // prevent container click to put carret at end this.input.click((function(__this) { var __func = function(e) { return e.stopPropagation(); }; return (function() { return __func.apply(__this, arguments); }); })(this)); // create element when place separator or paste this.input.keyup((function(__this) { var __func = function() { return this.parse_value(1); }; return (function() { return __func.apply(__this, arguments); }); })(this)); // focus input and set carret at and this.container.click((function(__this) { var __func = function() { this.input.focus(); return this.selection.set_caret_at_end(); }; return (function() { return __func.apply(__this, arguments); }); })(this)); // add element on press TAB or RETURN this.observer.bind([KEY.TAB, KEY.RETURN], (function(__this) { var __func = function(e) { if (this.autocomplete.val()) { e.preventDefault(); return this.add_and_reset(); } }; return (function() { return __func.apply(__this, arguments); }); })(this)); // remove last item this.observer.bind([KEY.BACKSPACE], (function(__this) { var __func = function(e) { var caret; if (this.values.length <= 0) { return null; } caret = this.selection.get_caret(); if (caret[0] === 0 && caret[1] === 0) { e.preventDefault(); return this.remove(this.values[this.values.length - 1]); } }; return (function() { return __func.apply(__this, arguments); }); })(this)); // hide complete box this.input.blur((function(__this) { var __func = function() { return setTimeout((function(__this) { var __func = function() { return this.autocomplete.hide_complete_box(); }; return (function() { return __func.apply(__this, arguments); }); })(this), 200); }; return (function() { return __func.apply(__this, arguments); }); })(this)); return this.observer.bind([KEY.ESCAPE], (function(__this) { var __func = function(e) { return this.autocomplete.hide_complete_box(); }; return (function() { return __func.apply(__this, arguments); }); })(this)); }; $.MultiSelect.prototype.values_real = function values_real() { return $.map(this.values, function(v) { return v[1]; }); }; $.MultiSelect.prototype.parse_value = function parse_value(min) { var _a, _b, _c, value, values; min = (typeof min !== "undefined" && min !== null) ? min : 0; values = this.input.val().split(this.options.separator); if (values.length > min) { _b = values; for (_a = 0, _c = _b.length; _a < _c; _a++) { value = _b[_a]; if (value.present()) { this.add([value, value]); } } this.input.val(""); return this.autocomplete.search(); } }; $.MultiSelect.prototype.add_and_reset = function add_and_reset() { if (this.autocomplete.val()) { this.add(this.autocomplete.val()); this.input.val(""); return this.autocomplete.search(); } }; // add new element $.MultiSelect.prototype.add = function add(value) { var a, close; if ($.inArray(value[1], this.values_real()) > -1) { return null; } if (value[0].blank()) { return null; } value[1] = value[1].trim(); this.values.push(value); a = $(document.createElement("a")); a.addClass("bit bit-box"); a.mouseover(function() { return $(this).addClass("bit-hover"); }); a.mouseout(function() { return $(this).removeClass("bit-hover"); }); a.data("value", value); a.html(value[0].entitizeHTML()); close = $(document.createElement("a")); close.addClass("closebutton"); close.click((function(__this) { var __func = function() { return this.remove(a.data("value")); }; return (function() { return __func.apply(__this, arguments); }); })(this)); a.append(close); this.input_wrapper.before(a); return this.refresh_hidden(); }; $.MultiSelect.prototype.remove = function remove(value) { this.values = $.grep(this.values, function(v) { return v[1] !== value[1]; }); this.container.find("a.bit-box").each(function() { if ($(this).data("value")[1] === value[1]) { return $(this).remove(); } }); return this.refresh_hidden(); }; $.MultiSelect.prototype.refresh_hidden = function refresh_hidden() { return this.hidden.val(this.values_real().join(this.options.separator)); }; // Input Observer Helper $.MultiSelect.InputObserver = function InputObserver(element) { this.input = $(element); this.input.keydown((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.handle_keydown, this, []))); this.events = []; return this; }; $.MultiSelect.InputObserver.prototype.bind = function bind(key, callback) { return this.events.push([key, callback]); }; $.MultiSelect.InputObserver.prototype.handle_keydown = function handle_keydown(e) { var _a, _b, _c, _d, _e, callback, event, keys; _a = []; _c = this.events; for (_b = 0, _d = _c.length; _b < _d; _b++) { event = _c[_b]; _a.push((function() { _e = event; keys = _e[0]; callback = _e[1]; if (!(keys.push)) { keys = [keys]; } if ($.inArray(e.keyCode, keys) > -1) { return callback(e); } }).call(this)); } return _a; }; // Selection Helper $.MultiSelect.Selection = function Selection(element) { this.input = $(element)[0]; return this; }; $.MultiSelect.Selection.prototype.get_caret = function get_caret() { var r; // For IE if (document.selection) { r = document.selection.createRange().duplicate(); r.moveEnd('character', this.input.value.length); if (r.text === '') { return [this.input.value.length, this.input.value.length]; } else { return [this.input.value.lastIndexOf(r.text), this.input.value.lastIndexOf(r.text)]; // Others } } else { return [this.input.selectionStart, this.input.selectionEnd]; } }; $.MultiSelect.Selection.prototype.set_caret = function set_caret(begin, end) { end = (typeof end !== "undefined" && end !== null) ? end : begin; this.input.selectionStart = begin; this.input.selectionEnd = end; return this.input.selectionEnd; }; $.MultiSelect.Selection.prototype.set_caret_at_end = function set_caret_at_end() { return this.set_caret(this.input.value.length); }; // Resizable Input Helper $.MultiSelect.ResizableInput = function ResizableInput(element) { this.input = $(element); this.create_measurer(); this.input.keypress((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.set_width, this, []))); this.input.keyup((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.set_width, this, []))); this.input.change((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.set_width, this, []))); return this; }; $.MultiSelect.ResizableInput.prototype.create_measurer = function create_measurer() { var measurer; if ($("#__jquery_multiselect_measurer")[0] === undefined) { measurer = $(document.createElement("div")); measurer.attr("id", "__jquery_multiselect_measurer"); measurer.css({ position: "absolute", left: "-1000px", top: "-1000px" }); $(document.body).append(measurer); } this.measurer = $("#__jquery_multiselect_measurer:first"); return this.measurer.css({ fontSize: this.input.css('font-size'), fontFamily: this.input.css('font-family') }); }; $.MultiSelect.ResizableInput.prototype.calculate_width = function calculate_width() { this.measurer.html(this.input.val().entitizeHTML() + 'MM'); return this.measurer.innerWidth(); }; $.MultiSelect.ResizableInput.prototype.set_width = function set_width() { return this.input.css("width", this.calculate_width() + "px"); }; // AutoComplete Helper $.MultiSelect.AutoComplete = function AutoComplete(multiselect, completions) { this.multiselect = multiselect; this.input = this.multiselect.input; this.completions = this.parse_completions(completions); this.matches = []; this.create_elements(); this.bind_events(); return this; }; $.MultiSelect.AutoComplete.prototype.parse_completions = function parse_completions(completions) { return $.map(completions, function(value) { if (typeof value === "string") { return [[value, value]]; } else if (value instanceof Array && value.length === 2) { return [value]; } else if (value.value && value.caption) { return [[value.caption, value.value]]; } else if (console) { return console.error("Invalid option " + (value)); } }); }; $.MultiSelect.AutoComplete.prototype.create_elements = function create_elements() { this.container = $(document.createElement("div")); this.container.addClass("jquery-multiselect-autocomplete"); this.container.css("width", this.multiselect.container.outerWidth()); this.container.css("display", "none"); this.container.append(this.def); this.list = $(document.createElement("ul")); this.list.addClass("feed"); this.container.append(this.list); return this.multiselect.container.after(this.container); }; $.MultiSelect.AutoComplete.prototype.bind_events = function bind_events() { this.input.keypress((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.search, this, []))); this.input.keyup((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.search, this, []))); this.input.change((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.search, this, []))); this.multiselect.observer.bind(KEY.UP, (function(__this) { var __func = function(e) { e.preventDefault(); return this.navigate_up(); }; return (function() { return __func.apply(__this, arguments); }); })(this)); return this.multiselect.observer.bind(KEY.DOWN, (function(__this) { var __func = function(e) { e.preventDefault(); return this.navigate_down(); }; return (function() { return __func.apply(__this, arguments); }); })(this)); }; $.MultiSelect.AutoComplete.prototype.search = function search() { var _a, _b, def, i, item, option, x; if (this.input.val().trim() === this.query) { return null; } // dont do operation if query is same this.query = this.input.val().trim(); this.list.html(""); // clear list this.current = 0; if (this.query.present()) { this.container.fadeIn("fast"); this.matches = this.matching_completions(this.query); if (this.multiselect.options.enable_new_options) { def = this.create_item("Add <em>" + this.query + "</em>"); def.mouseover((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.select_index, this, [0]))); } _a = this.matches; for (i = 0, _b = _a.length; i < _b; i++) { option = _a[i]; x = this.multiselect.options.enable_new_options ? i + 1 : i; item = this.create_item(this.highlight(option[0], this.query)); item.mouseover((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.select_index, this, [x]))); } if (this.multiselect.options.enable_new_options) { this.matches.unshift([this.query, this.query]); } return this.select_index(0); } else { this.matches = []; this.hide_complete_box(); this.query = null; return this.query; } }; $.MultiSelect.AutoComplete.prototype.hide_complete_box = function hide_complete_box() { return this.container.fadeOut("fast"); }; $.MultiSelect.AutoComplete.prototype.select_index = function select_index(index) { var items; items = this.list.find("li"); items.removeClass("auto-focus"); items.filter(":eq(" + (index) + ")").addClass("auto-focus"); this.current = index; return this.current; }; $.MultiSelect.AutoComplete.prototype.navigate_down = function navigate_down() { var next; next = this.current + 1; if (next >= this.matches.length) { next = 0; } return this.select_index(next); }; $.MultiSelect.AutoComplete.prototype.navigate_up = function navigate_up() { var next; next = this.current - 1; if (next < 0) { next = this.matches.length - 1; } return this.select_index(next); }; $.MultiSelect.AutoComplete.prototype.create_item = function create_item(text, highlight) { var item; item = $(document.createElement("li")); item.click((function(__this) { var __func = function() { this.multiselect.add_and_reset(); this.search(); return this.input.focus(); }; return (function() { return __func.apply(__this, arguments); }); })(this)); item.html(text); this.list.append(item); return item; }; $.MultiSelect.AutoComplete.prototype.val = function val() { return this.matches[this.current]; }; $.MultiSelect.AutoComplete.prototype.highlight = function highlight(text, highlight) { - var reg; - reg = "(" + (RegExp.escape(highlight)) + ")"; - return text.replace(new RegExp(reg, "gi"), '<em>$1</em>'); + var _a, _b, _c, char, current, highlighted, reg; + if (this.multiselect.options.complex_search) { + highlighted = ""; + current = 0; + _b = text; + for (_a = 0, _c = _b.length; _a < _c; _a++) { + char = _b[_a]; + if (current < highlight.length && char.toLowerCase() === highlight[current].toLowerCase()) { + highlighted += "<em>" + (char) + "</em>"; + current++; + } else { + highlighted += char; + } + } + return highlighted; + } else { + reg = "(" + (RegExp.escape(highlight)) + ")"; + return text.replace(new RegExp(reg, "gi"), '<em>$1</em>'); + } }; $.MultiSelect.AutoComplete.prototype.matching_completions = function matching_completions(text) { - var count, reg; - reg = new RegExp(RegExp.escape(text), "i"); + var _a, _b, _c, char, count, reg; + if (this.multiselect.options.complex_search) { + reg = ""; + _b = text; + for (_a = 0, _c = _b.length; _a < _c; _a++) { + char = _b[_a]; + reg += RegExp.escape(char) + ".*"; + } + reg = new RegExp(reg, "i"); + } else { + reg = new RegExp(RegExp.escape(text), "i"); + } count = 0; return $.grep(this.completions, (function(__this) { var __func = function(c) { if (count >= this.multiselect.options.max_complete_results) { return false; } if ($.inArray(c[1], this.multiselect.values_real()) > -1) { return false; } if (c[0].match(reg)) { count++; return true; } else { return false; } }; return (function() { return __func.apply(__this, arguments); }); })(this)); }; // Hook jQuery extension $.fn.multiselect = function multiselect(options) { options = (typeof options !== "undefined" && options !== null) ? options : {}; return $(this).each(function() { var _a, _b, _c, completions, input, option, select_options; if (this.tagName.toLowerCase() === "select") { input = $(document.createElement("input")); input.attr("type", "text"); input.attr("name", this.name); input.attr("id", this.id); completions = []; _b = this.options; for (_a = 0, _c = _b.length; _a < _c; _a++) { option = _b[_a]; completions.push([option.innerHTML, option.value]); } select_options = { completions: completions, enable_new_options: false }; $.extend(select_options, options); $(this).replaceWith(input); return new $.MultiSelect(input, select_options); } else if (this.tagName.toLowerCase() === "input" && this.type === "text") { return new $.MultiSelect(this, options); } }); }; return $.fn.multiselect; })(jQuery); $.extend(String.prototype, { trim: function trim() { return this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, ''); }, entitizeHTML: function entitizeHTML() { return this.replace(/</g, '&lt;').replace(/>/g, '&gt;'); }, unentitizeHTML: function unentitizeHTML() { return this.replace(/&lt;/g, '<').replace(/&gt;/g, '>'); }, blank: function blank() { return this.trim().length === 0; }, present: function present() { return !this.blank(); } }); RegExp.escape = function escape(str) { return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); }; \ No newline at end of file diff --git a/src/jquery.multiselect.coffee b/src/jquery.multiselect.coffee index 5f07ff5..c688a9f 100644 --- a/src/jquery.multiselect.coffee +++ b/src/jquery.multiselect.coffee @@ -1,395 +1,416 @@ # Copyright (c) 2010 Wilker Lúcio # # 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. (($) -> KEY: { BACKSPACE: 8 TAB: 9 RETURN: 13 ESCAPE: 27 SPACE: 32 LEFT: 37 UP: 38 RIGHT: 39 DOWN: 40 COLON: 188 DOT: 190 } class $.MultiSelect constructor: (element, options) -> @options: { separator: "," completions: [] max_complete_results: 5 enable_new_options: true + complex_search: true } $.extend(@options, options || {}) @values: [] @input: $(element) @initialize_elements() @initialize_events() @parse_value() initialize_elements: -> # hidden input to hold real value @hidden: $(document.createElement("input")) @hidden.attr("name", @input.attr("name")) @hidden.attr("type", "hidden") @input.removeAttr("name") @container: $(document.createElement("div")) @container.addClass("jquery-multiselect") @input_wrapper: $(document.createElement("a")) @input_wrapper.addClass("bit-input") @input.replaceWith(@container) @container.append(@input_wrapper) @input_wrapper.append(@input) @container.before(@hidden) initialize_events: -> # create helpers @selection: new $.MultiSelect.Selection(@input) @resizable: new $.MultiSelect.ResizableInput(@input) @observer: new $.MultiSelect.InputObserver(@input) @autocomplete: new $.MultiSelect.AutoComplete(this, @options.completions) # prevent container click to put carret at end @input.click (e) => e.stopPropagation() # create element when place separator or paste @input.keyup => @parse_value(1) # focus input and set carret at and @container.click => @input.focus() @selection.set_caret_at_end() # add element on press TAB or RETURN @observer.bind [KEY.TAB, KEY.RETURN], (e) => if @autocomplete.val() e.preventDefault() @add_and_reset() # remove last item @observer.bind [KEY.BACKSPACE], (e) => return if @values.length <= 0 caret = @selection.get_caret() if caret[0] == 0 and caret[1] == 0 e.preventDefault() @remove(@values[@values.length - 1]) # hide complete box @input.blur => setTimeout(=> @autocomplete.hide_complete_box() 200) @observer.bind [KEY.ESCAPE], (e) => @autocomplete.hide_complete_box() values_real: -> $.map @values, (v) -> v[1] parse_value: (min) -> min ?= 0 values: @input.val().split(@options.separator) if values.length > min for value in values @add [value, value] if value.present() @input.val("") @autocomplete.search() add_and_reset: -> if @autocomplete.val() @add(@autocomplete.val()) @input.val("") @autocomplete.search() # add new element add: (value) -> return if $.inArray(value[1], @values_real()) > -1 return if value[0].blank() value[1] = value[1].trim() @values.push(value) a: $(document.createElement("a")) a.addClass("bit bit-box") a.mouseover -> $(this).addClass("bit-hover") a.mouseout -> $(this).removeClass("bit-hover") a.data("value", value) a.html(value[0].entitizeHTML()) close: $(document.createElement("a")) close.addClass("closebutton") close.click => @remove(a.data("value")) a.append(close) @input_wrapper.before(a) @refresh_hidden() remove: (value) -> @values: $.grep @values, (v) -> v[1] != value[1] @container.find("a.bit-box").each -> $(this).remove() if $(this).data("value")[1] == value[1] @refresh_hidden() refresh_hidden: -> @hidden.val(@values_real().join(@options.separator)) # Input Observer Helper class $.MultiSelect.InputObserver constructor: (element) -> @input: $(element) @input.keydown(@handle_keydown <- this) @events: [] bind: (key, callback) -> @events.push([key, callback]) handle_keydown: (e) -> for event in @events [keys, callback]: event keys: [keys] unless keys.push callback(e) if $.inArray(e.keyCode, keys) > -1 # Selection Helper class $.MultiSelect.Selection constructor: (element) -> @input: $(element)[0] get_caret: -> # For IE if document.selection r: document.selection.createRange().duplicate() r.moveEnd('character', @input.value.length) if r.text == '' [@input.value.length, @input.value.length] else [@input.value.lastIndexOf(r.text), @input.value.lastIndexOf(r.text)] # Others else [@input.selectionStart, @input.selectionEnd] set_caret: (begin, end) -> end ?= begin @input.selectionStart: begin @input.selectionEnd: end set_caret_at_end: -> @set_caret(@input.value.length) # Resizable Input Helper class $.MultiSelect.ResizableInput constructor: (element) -> @input: $(element) @create_measurer() @input.keypress(@set_width <- this) @input.keyup(@set_width <- this) @input.change(@set_width <- this) create_measurer: -> if $("#__jquery_multiselect_measurer")[0] == undefined measurer: $(document.createElement("div")) measurer.attr("id", "__jquery_multiselect_measurer") measurer.css { position: "absolute" left: "-1000px" top: "-1000px" } $(document.body).append(measurer) @measurer: $("#__jquery_multiselect_measurer:first") @measurer.css { fontSize: @input.css('font-size') fontFamily: @input.css('font-family') } calculate_width: -> @measurer.html(@input.val().entitizeHTML() + 'MM') @measurer.innerWidth() set_width: -> @input.css("width", @calculate_width() + "px") # AutoComplete Helper class $.MultiSelect.AutoComplete constructor: (multiselect, completions) -> @multiselect: multiselect @input: @multiselect.input @completions: @parse_completions(completions) @matches: [] @create_elements() @bind_events() parse_completions: (completions) -> $.map completions, (value) -> if typeof value == "string" [[value, value]] else if value instanceof Array and value.length == 2 [value] else if value.value and value.caption [[value.caption, value.value]] else console.error "Invalid option ${value}" if console create_elements: -> @container: $(document.createElement("div")) @container.addClass("jquery-multiselect-autocomplete") @container.css("width", @multiselect.container.outerWidth()) @container.css("display", "none") @container.append(@def) @list: $(document.createElement("ul")) @list.addClass("feed") @container.append(@list) @multiselect.container.after(@container) bind_events: -> @input.keypress(@search <- this) @input.keyup(@search <- this) @input.change(@search <- this) @multiselect.observer.bind KEY.UP, (e) => e.preventDefault(); @navigate_up() @multiselect.observer.bind KEY.DOWN, (e) => e.preventDefault(); @navigate_down() search: -> return if @input.val().trim() == @query # dont do operation if query is same @query: @input.val().trim() @list.html("") # clear list @current: 0 if @query.present() @container.fadeIn("fast") @matches: @matching_completions(@query) if @multiselect.options.enable_new_options def: @create_item("Add <em>" + @query + "</em>") def.mouseover(@select_index <- this, 0) for option, i in @matches x: if @multiselect.options.enable_new_options then i + 1 else i item: @create_item(@highlight(option[0], @query)) item.mouseover(@select_index <- this, x) @matches.unshift([@query, @query]) if @multiselect.options.enable_new_options @select_index(0) else @matches: [] @hide_complete_box() @query: null hide_complete_box: -> @container.fadeOut("fast") select_index: (index) -> items: @list.find("li") items.removeClass("auto-focus") items.filter(":eq(${index})").addClass("auto-focus") @current: index navigate_down: -> next: @current + 1 next: 0 if next >= @matches.length @select_index(next) navigate_up: -> next: @current - 1 next: @matches.length - 1 if next < 0 @select_index(next) create_item: (text, highlight) -> item: $(document.createElement("li")) item.click => @multiselect.add_and_reset() @search() @input.focus() item.html(text) @list.append(item) item val: -> @matches[@current] highlight: (text, highlight) -> - reg: "(${RegExp.escape(highlight)})" - text.replace(new RegExp(reg, "gi"), '<em>$1</em>') + if @multiselect.options.complex_search + highlighted: "" + current: 0 + + for char in text + if current < highlight.length and char.toLowerCase() == highlight[current].toLowerCase() + highlighted += "<em>${char}</em>" + current++ + else + highlighted += char + + highlighted + else + reg: "(${RegExp.escape(highlight)})" + text.replace(new RegExp(reg, "gi"), '<em>$1</em>') matching_completions: (text) -> - reg: new RegExp(RegExp.escape(text), "i") + if @multiselect.options.complex_search + reg: "" + for char in text + reg += RegExp.escape(char) + ".*" + + reg: new RegExp(reg, "i") + else + reg: new RegExp(RegExp.escape(text), "i") count: 0 $.grep @completions, (c) => return false if count >= @multiselect.options.max_complete_results return false if $.inArray(c[1], @multiselect.values_real()) > -1 if c[0].match(reg) count++ true else false # Hook jQuery extension $.fn.multiselect: (options) -> options ?= {} $(this).each -> if this.tagName.toLowerCase() == "select" input: $(document.createElement("input")) input.attr("type", "text") input.attr("name", this.name) input.attr("id", this.id) completions: [] for option in this.options completions.push([option.innerHTML, option.value]) select_options: { completions: completions enable_new_options: false } $.extend(select_options, options) $(this).replaceWith(input) new $.MultiSelect(input, select_options) else if this.tagName.toLowerCase() == "input" and this.type == "text" new $.MultiSelect(this, options) )(jQuery) $.extend String.prototype, { trim: -> this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, '') entitizeHTML: -> this.replace(/</g,'&lt;').replace(/>/g,'&gt;') unentitizeHTML: -> this.replace(/&lt;/g,'<').replace(/&gt;/g,'>') blank: -> this.trim().length == 0 present: -> not @blank() }; RegExp.escape: (str) -> String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
wilkerlucio/jquery-multiselect
02058d6da3ae3f621e07435d63810fcd6f479c11
hide autocomplete box when esc and blur, and added some effects
diff --git a/js/jquery.multiselect.js b/js/jquery.multiselect.js index fecfe2a..cbb3c1a 100644 --- a/js/jquery.multiselect.js +++ b/js/jquery.multiselect.js @@ -1,542 +1,570 @@ // Copyright (c) 2010 Wilker Lúcio // // 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. (function($) { var KEY; KEY = { BACKSPACE: 8, TAB: 9, RETURN: 13, ESCAPE: 27, SPACE: 32, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, COLON: 188, DOT: 190 }; $.MultiSelect = function MultiSelect(element, options) { this.options = { separator: ",", completions: [], max_complete_results: 5, enable_new_options: true }; $.extend(this.options, options || {}); this.values = []; this.input = $(element); this.initialize_elements(); this.initialize_events(); this.parse_value(); return this; }; $.MultiSelect.prototype.initialize_elements = function initialize_elements() { // hidden input to hold real value this.hidden = $(document.createElement("input")); this.hidden.attr("name", this.input.attr("name")); this.hidden.attr("type", "hidden"); this.input.removeAttr("name"); this.container = $(document.createElement("div")); this.container.addClass("jquery-multiselect"); this.input_wrapper = $(document.createElement("a")); this.input_wrapper.addClass("bit-input"); this.input.replaceWith(this.container); this.container.append(this.input_wrapper); this.input_wrapper.append(this.input); return this.container.before(this.hidden); }; $.MultiSelect.prototype.initialize_events = function initialize_events() { // create helpers this.selection = new $.MultiSelect.Selection(this.input); this.resizable = new $.MultiSelect.ResizableInput(this.input); this.observer = new $.MultiSelect.InputObserver(this.input); this.autocomplete = new $.MultiSelect.AutoComplete(this, this.options.completions); // prevent container click to put carret at end this.input.click((function(__this) { var __func = function(e) { return e.stopPropagation(); }; return (function() { return __func.apply(__this, arguments); }); })(this)); // create element when place separator or paste this.input.keyup((function(__this) { var __func = function() { return this.parse_value(1); }; return (function() { return __func.apply(__this, arguments); }); })(this)); // focus input and set carret at and this.container.click((function(__this) { var __func = function() { this.input.focus(); return this.selection.set_caret_at_end(); }; return (function() { return __func.apply(__this, arguments); }); })(this)); // add element on press TAB or RETURN this.observer.bind([KEY.TAB, KEY.RETURN], (function(__this) { var __func = function(e) { if (this.autocomplete.val()) { e.preventDefault(); return this.add_and_reset(); } }; return (function() { return __func.apply(__this, arguments); }); })(this)); - return this.observer.bind([KEY.BACKSPACE], (function(__this) { + // remove last item + this.observer.bind([KEY.BACKSPACE], (function(__this) { var __func = function(e) { var caret; if (this.values.length <= 0) { return null; } caret = this.selection.get_caret(); if (caret[0] === 0 && caret[1] === 0) { e.preventDefault(); return this.remove(this.values[this.values.length - 1]); } }; return (function() { return __func.apply(__this, arguments); }); })(this)); + // hide complete box + this.input.blur((function(__this) { + var __func = function() { + return setTimeout((function(__this) { + var __func = function() { + return this.autocomplete.hide_complete_box(); + }; + return (function() { + return __func.apply(__this, arguments); + }); + })(this), 200); + }; + return (function() { + return __func.apply(__this, arguments); + }); + })(this)); + return this.observer.bind([KEY.ESCAPE], (function(__this) { + var __func = function(e) { + return this.autocomplete.hide_complete_box(); + }; + return (function() { + return __func.apply(__this, arguments); + }); + })(this)); }; $.MultiSelect.prototype.values_real = function values_real() { return $.map(this.values, function(v) { return v[1]; }); }; $.MultiSelect.prototype.parse_value = function parse_value(min) { var _a, _b, _c, value, values; min = (typeof min !== "undefined" && min !== null) ? min : 0; values = this.input.val().split(this.options.separator); if (values.length > min) { _b = values; for (_a = 0, _c = _b.length; _a < _c; _a++) { value = _b[_a]; if (value.present()) { this.add([value, value]); } } this.input.val(""); return this.autocomplete.search(); } }; $.MultiSelect.prototype.add_and_reset = function add_and_reset() { if (this.autocomplete.val()) { this.add(this.autocomplete.val()); this.input.val(""); return this.autocomplete.search(); } }; // add new element $.MultiSelect.prototype.add = function add(value) { var a, close; if ($.inArray(value[1], this.values_real()) > -1) { return null; } if (value[0].blank()) { return null; } value[1] = value[1].trim(); this.values.push(value); a = $(document.createElement("a")); a.addClass("bit bit-box"); a.mouseover(function() { return $(this).addClass("bit-hover"); }); a.mouseout(function() { return $(this).removeClass("bit-hover"); }); a.data("value", value); a.html(value[0].entitizeHTML()); close = $(document.createElement("a")); close.addClass("closebutton"); close.click((function(__this) { var __func = function() { return this.remove(a.data("value")); }; return (function() { return __func.apply(__this, arguments); }); })(this)); a.append(close); this.input_wrapper.before(a); return this.refresh_hidden(); }; $.MultiSelect.prototype.remove = function remove(value) { this.values = $.grep(this.values, function(v) { return v[1] !== value[1]; }); this.container.find("a.bit-box").each(function() { if ($(this).data("value")[1] === value[1]) { return $(this).remove(); } }); return this.refresh_hidden(); }; $.MultiSelect.prototype.refresh_hidden = function refresh_hidden() { return this.hidden.val(this.values_real().join(this.options.separator)); }; // Input Observer Helper $.MultiSelect.InputObserver = function InputObserver(element) { this.input = $(element); this.input.keydown((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.handle_keydown, this, []))); this.events = []; return this; }; $.MultiSelect.InputObserver.prototype.bind = function bind(key, callback) { return this.events.push([key, callback]); }; $.MultiSelect.InputObserver.prototype.handle_keydown = function handle_keydown(e) { var _a, _b, _c, _d, _e, callback, event, keys; _a = []; _c = this.events; for (_b = 0, _d = _c.length; _b < _d; _b++) { event = _c[_b]; _a.push((function() { _e = event; keys = _e[0]; callback = _e[1]; if (!(keys.push)) { keys = [keys]; } if ($.inArray(e.keyCode, keys) > -1) { return callback(e); } }).call(this)); } return _a; }; // Selection Helper $.MultiSelect.Selection = function Selection(element) { this.input = $(element)[0]; return this; }; $.MultiSelect.Selection.prototype.get_caret = function get_caret() { var r; // For IE if (document.selection) { r = document.selection.createRange().duplicate(); r.moveEnd('character', this.input.value.length); if (r.text === '') { return [this.input.value.length, this.input.value.length]; } else { return [this.input.value.lastIndexOf(r.text), this.input.value.lastIndexOf(r.text)]; // Others } } else { return [this.input.selectionStart, this.input.selectionEnd]; } }; $.MultiSelect.Selection.prototype.set_caret = function set_caret(begin, end) { end = (typeof end !== "undefined" && end !== null) ? end : begin; this.input.selectionStart = begin; this.input.selectionEnd = end; return this.input.selectionEnd; }; $.MultiSelect.Selection.prototype.set_caret_at_end = function set_caret_at_end() { return this.set_caret(this.input.value.length); }; // Resizable Input Helper $.MultiSelect.ResizableInput = function ResizableInput(element) { this.input = $(element); this.create_measurer(); this.input.keypress((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.set_width, this, []))); this.input.keyup((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.set_width, this, []))); this.input.change((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.set_width, this, []))); return this; }; $.MultiSelect.ResizableInput.prototype.create_measurer = function create_measurer() { var measurer; if ($("#__jquery_multiselect_measurer")[0] === undefined) { measurer = $(document.createElement("div")); measurer.attr("id", "__jquery_multiselect_measurer"); measurer.css({ position: "absolute", left: "-1000px", top: "-1000px" }); $(document.body).append(measurer); } this.measurer = $("#__jquery_multiselect_measurer:first"); return this.measurer.css({ fontSize: this.input.css('font-size'), fontFamily: this.input.css('font-family') }); }; $.MultiSelect.ResizableInput.prototype.calculate_width = function calculate_width() { this.measurer.html(this.input.val().entitizeHTML() + 'MM'); return this.measurer.innerWidth(); }; $.MultiSelect.ResizableInput.prototype.set_width = function set_width() { return this.input.css("width", this.calculate_width() + "px"); }; // AutoComplete Helper $.MultiSelect.AutoComplete = function AutoComplete(multiselect, completions) { this.multiselect = multiselect; this.input = this.multiselect.input; this.completions = this.parse_completions(completions); this.matches = []; this.create_elements(); this.bind_events(); return this; }; $.MultiSelect.AutoComplete.prototype.parse_completions = function parse_completions(completions) { return $.map(completions, function(value) { if (typeof value === "string") { return [[value, value]]; } else if (value instanceof Array && value.length === 2) { return [value]; } else if (value.value && value.caption) { return [[value.caption, value.value]]; } else if (console) { return console.error("Invalid option " + (value)); } }); }; $.MultiSelect.AutoComplete.prototype.create_elements = function create_elements() { this.container = $(document.createElement("div")); this.container.addClass("jquery-multiselect-autocomplete"); this.container.css("width", this.multiselect.container.outerWidth()); this.container.css("display", "none"); this.container.append(this.def); this.list = $(document.createElement("ul")); this.list.addClass("feed"); this.container.append(this.list); return this.multiselect.container.after(this.container); }; $.MultiSelect.AutoComplete.prototype.bind_events = function bind_events() { this.input.keypress((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.search, this, []))); this.input.keyup((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.search, this, []))); this.input.change((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.search, this, []))); this.multiselect.observer.bind(KEY.UP, (function(__this) { var __func = function(e) { e.preventDefault(); return this.navigate_up(); }; return (function() { return __func.apply(__this, arguments); }); })(this)); return this.multiselect.observer.bind(KEY.DOWN, (function(__this) { var __func = function(e) { e.preventDefault(); return this.navigate_down(); }; return (function() { return __func.apply(__this, arguments); }); })(this)); }; $.MultiSelect.AutoComplete.prototype.search = function search() { var _a, _b, def, i, item, option, x; if (this.input.val().trim() === this.query) { return null; } // dont do operation if query is same this.query = this.input.val().trim(); this.list.html(""); // clear list this.current = 0; if (this.query.present()) { - this.container.css("display", "block"); + this.container.fadeIn("fast"); this.matches = this.matching_completions(this.query); if (this.multiselect.options.enable_new_options) { def = this.create_item("Add <em>" + this.query + "</em>"); def.mouseover((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.select_index, this, [0]))); } _a = this.matches; for (i = 0, _b = _a.length; i < _b; i++) { option = _a[i]; x = this.multiselect.options.enable_new_options ? i + 1 : i; item = this.create_item(this.highlight(option[0], this.query)); item.mouseover((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.select_index, this, [x]))); } if (this.multiselect.options.enable_new_options) { this.matches.unshift([this.query, this.query]); } return this.select_index(0); } else { this.matches = []; - this.container.css("display", "none"); + this.hide_complete_box(); this.query = null; return this.query; } }; + $.MultiSelect.AutoComplete.prototype.hide_complete_box = function hide_complete_box() { + return this.container.fadeOut("fast"); + }; $.MultiSelect.AutoComplete.prototype.select_index = function select_index(index) { var items; items = this.list.find("li"); items.removeClass("auto-focus"); items.filter(":eq(" + (index) + ")").addClass("auto-focus"); this.current = index; return this.current; }; $.MultiSelect.AutoComplete.prototype.navigate_down = function navigate_down() { var next; next = this.current + 1; if (next >= this.matches.length) { next = 0; } return this.select_index(next); }; $.MultiSelect.AutoComplete.prototype.navigate_up = function navigate_up() { var next; next = this.current - 1; if (next < 0) { next = this.matches.length - 1; } return this.select_index(next); }; $.MultiSelect.AutoComplete.prototype.create_item = function create_item(text, highlight) { var item; item = $(document.createElement("li")); item.click((function(__this) { var __func = function() { this.multiselect.add_and_reset(); this.search(); return this.input.focus(); }; return (function() { return __func.apply(__this, arguments); }); })(this)); item.html(text); this.list.append(item); return item; }; $.MultiSelect.AutoComplete.prototype.val = function val() { return this.matches[this.current]; }; $.MultiSelect.AutoComplete.prototype.highlight = function highlight(text, highlight) { var reg; reg = "(" + (RegExp.escape(highlight)) + ")"; return text.replace(new RegExp(reg, "gi"), '<em>$1</em>'); }; $.MultiSelect.AutoComplete.prototype.matching_completions = function matching_completions(text) { var count, reg; reg = new RegExp(RegExp.escape(text), "i"); count = 0; return $.grep(this.completions, (function(__this) { var __func = function(c) { if (count >= this.multiselect.options.max_complete_results) { return false; } if ($.inArray(c[1], this.multiselect.values_real()) > -1) { return false; } if (c[0].match(reg)) { count++; return true; } else { return false; } }; return (function() { return __func.apply(__this, arguments); }); })(this)); }; // Hook jQuery extension $.fn.multiselect = function multiselect(options) { options = (typeof options !== "undefined" && options !== null) ? options : {}; return $(this).each(function() { var _a, _b, _c, completions, input, option, select_options; if (this.tagName.toLowerCase() === "select") { input = $(document.createElement("input")); input.attr("type", "text"); input.attr("name", this.name); input.attr("id", this.id); completions = []; _b = this.options; for (_a = 0, _c = _b.length; _a < _c; _a++) { option = _b[_a]; completions.push([option.innerHTML, option.value]); } select_options = { completions: completions, enable_new_options: false }; $.extend(select_options, options); $(this).replaceWith(input); return new $.MultiSelect(input, select_options); } else if (this.tagName.toLowerCase() === "input" && this.type === "text") { return new $.MultiSelect(this, options); } }); }; return $.fn.multiselect; })(jQuery); $.extend(String.prototype, { trim: function trim() { return this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, ''); }, entitizeHTML: function entitizeHTML() { return this.replace(/</g, '&lt;').replace(/>/g, '&gt;'); }, unentitizeHTML: function unentitizeHTML() { return this.replace(/&lt;/g, '<').replace(/&gt;/g, '>'); }, blank: function blank() { return this.trim().length === 0; }, present: function present() { return !this.blank(); } }); RegExp.escape = function escape(str) { return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); }; \ No newline at end of file diff --git a/src/jquery.multiselect.coffee b/src/jquery.multiselect.coffee index 6909764..5f07ff5 100644 --- a/src/jquery.multiselect.coffee +++ b/src/jquery.multiselect.coffee @@ -1,382 +1,395 @@ # Copyright (c) 2010 Wilker Lúcio # # 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. (($) -> KEY: { BACKSPACE: 8 TAB: 9 RETURN: 13 ESCAPE: 27 SPACE: 32 LEFT: 37 UP: 38 RIGHT: 39 DOWN: 40 COLON: 188 DOT: 190 } class $.MultiSelect constructor: (element, options) -> @options: { separator: "," completions: [] max_complete_results: 5 enable_new_options: true } $.extend(@options, options || {}) @values: [] @input: $(element) @initialize_elements() @initialize_events() @parse_value() initialize_elements: -> # hidden input to hold real value @hidden: $(document.createElement("input")) @hidden.attr("name", @input.attr("name")) @hidden.attr("type", "hidden") @input.removeAttr("name") @container: $(document.createElement("div")) @container.addClass("jquery-multiselect") @input_wrapper: $(document.createElement("a")) @input_wrapper.addClass("bit-input") @input.replaceWith(@container) @container.append(@input_wrapper) @input_wrapper.append(@input) @container.before(@hidden) initialize_events: -> # create helpers @selection: new $.MultiSelect.Selection(@input) @resizable: new $.MultiSelect.ResizableInput(@input) @observer: new $.MultiSelect.InputObserver(@input) @autocomplete: new $.MultiSelect.AutoComplete(this, @options.completions) # prevent container click to put carret at end @input.click (e) => e.stopPropagation() # create element when place separator or paste @input.keyup => @parse_value(1) # focus input and set carret at and @container.click => @input.focus() @selection.set_caret_at_end() # add element on press TAB or RETURN @observer.bind [KEY.TAB, KEY.RETURN], (e) => if @autocomplete.val() e.preventDefault() @add_and_reset() + # remove last item @observer.bind [KEY.BACKSPACE], (e) => return if @values.length <= 0 caret = @selection.get_caret() if caret[0] == 0 and caret[1] == 0 e.preventDefault() @remove(@values[@values.length - 1]) + + # hide complete box + @input.blur => + setTimeout(=> + @autocomplete.hide_complete_box() + 200) + + @observer.bind [KEY.ESCAPE], (e) => + @autocomplete.hide_complete_box() values_real: -> $.map @values, (v) -> v[1] parse_value: (min) -> min ?= 0 values: @input.val().split(@options.separator) if values.length > min for value in values @add [value, value] if value.present() @input.val("") @autocomplete.search() add_and_reset: -> if @autocomplete.val() @add(@autocomplete.val()) @input.val("") @autocomplete.search() # add new element add: (value) -> return if $.inArray(value[1], @values_real()) > -1 return if value[0].blank() value[1] = value[1].trim() @values.push(value) a: $(document.createElement("a")) a.addClass("bit bit-box") a.mouseover -> $(this).addClass("bit-hover") a.mouseout -> $(this).removeClass("bit-hover") a.data("value", value) a.html(value[0].entitizeHTML()) close: $(document.createElement("a")) close.addClass("closebutton") close.click => @remove(a.data("value")) a.append(close) @input_wrapper.before(a) @refresh_hidden() remove: (value) -> @values: $.grep @values, (v) -> v[1] != value[1] @container.find("a.bit-box").each -> $(this).remove() if $(this).data("value")[1] == value[1] @refresh_hidden() refresh_hidden: -> @hidden.val(@values_real().join(@options.separator)) # Input Observer Helper class $.MultiSelect.InputObserver constructor: (element) -> @input: $(element) @input.keydown(@handle_keydown <- this) @events: [] bind: (key, callback) -> @events.push([key, callback]) handle_keydown: (e) -> for event in @events [keys, callback]: event keys: [keys] unless keys.push callback(e) if $.inArray(e.keyCode, keys) > -1 # Selection Helper class $.MultiSelect.Selection constructor: (element) -> @input: $(element)[0] get_caret: -> # For IE if document.selection r: document.selection.createRange().duplicate() r.moveEnd('character', @input.value.length) if r.text == '' [@input.value.length, @input.value.length] else [@input.value.lastIndexOf(r.text), @input.value.lastIndexOf(r.text)] # Others else [@input.selectionStart, @input.selectionEnd] set_caret: (begin, end) -> end ?= begin @input.selectionStart: begin @input.selectionEnd: end set_caret_at_end: -> @set_caret(@input.value.length) # Resizable Input Helper class $.MultiSelect.ResizableInput constructor: (element) -> @input: $(element) @create_measurer() @input.keypress(@set_width <- this) @input.keyup(@set_width <- this) @input.change(@set_width <- this) create_measurer: -> if $("#__jquery_multiselect_measurer")[0] == undefined measurer: $(document.createElement("div")) measurer.attr("id", "__jquery_multiselect_measurer") measurer.css { position: "absolute" left: "-1000px" top: "-1000px" } $(document.body).append(measurer) @measurer: $("#__jquery_multiselect_measurer:first") @measurer.css { fontSize: @input.css('font-size') fontFamily: @input.css('font-family') } calculate_width: -> @measurer.html(@input.val().entitizeHTML() + 'MM') @measurer.innerWidth() set_width: -> @input.css("width", @calculate_width() + "px") # AutoComplete Helper class $.MultiSelect.AutoComplete constructor: (multiselect, completions) -> @multiselect: multiselect @input: @multiselect.input @completions: @parse_completions(completions) @matches: [] @create_elements() @bind_events() parse_completions: (completions) -> $.map completions, (value) -> if typeof value == "string" [[value, value]] else if value instanceof Array and value.length == 2 [value] else if value.value and value.caption [[value.caption, value.value]] else console.error "Invalid option ${value}" if console create_elements: -> @container: $(document.createElement("div")) @container.addClass("jquery-multiselect-autocomplete") @container.css("width", @multiselect.container.outerWidth()) @container.css("display", "none") @container.append(@def) @list: $(document.createElement("ul")) @list.addClass("feed") @container.append(@list) @multiselect.container.after(@container) bind_events: -> @input.keypress(@search <- this) @input.keyup(@search <- this) @input.change(@search <- this) @multiselect.observer.bind KEY.UP, (e) => e.preventDefault(); @navigate_up() @multiselect.observer.bind KEY.DOWN, (e) => e.preventDefault(); @navigate_down() search: -> return if @input.val().trim() == @query # dont do operation if query is same @query: @input.val().trim() @list.html("") # clear list @current: 0 if @query.present() - @container.css("display", "block") + @container.fadeIn("fast") @matches: @matching_completions(@query) if @multiselect.options.enable_new_options def: @create_item("Add <em>" + @query + "</em>") def.mouseover(@select_index <- this, 0) for option, i in @matches x: if @multiselect.options.enable_new_options then i + 1 else i item: @create_item(@highlight(option[0], @query)) item.mouseover(@select_index <- this, x) @matches.unshift([@query, @query]) if @multiselect.options.enable_new_options @select_index(0) else @matches: [] - @container.css("display", "none") + @hide_complete_box() @query: null + hide_complete_box: -> + @container.fadeOut("fast") + select_index: (index) -> items: @list.find("li") items.removeClass("auto-focus") items.filter(":eq(${index})").addClass("auto-focus") @current: index navigate_down: -> next: @current + 1 next: 0 if next >= @matches.length @select_index(next) navigate_up: -> next: @current - 1 next: @matches.length - 1 if next < 0 @select_index(next) create_item: (text, highlight) -> item: $(document.createElement("li")) item.click => @multiselect.add_and_reset() @search() @input.focus() item.html(text) @list.append(item) item val: -> @matches[@current] highlight: (text, highlight) -> reg: "(${RegExp.escape(highlight)})" text.replace(new RegExp(reg, "gi"), '<em>$1</em>') matching_completions: (text) -> reg: new RegExp(RegExp.escape(text), "i") count: 0 $.grep @completions, (c) => return false if count >= @multiselect.options.max_complete_results return false if $.inArray(c[1], @multiselect.values_real()) > -1 if c[0].match(reg) count++ true else false # Hook jQuery extension $.fn.multiselect: (options) -> options ?= {} $(this).each -> if this.tagName.toLowerCase() == "select" input: $(document.createElement("input")) input.attr("type", "text") input.attr("name", this.name) input.attr("id", this.id) completions: [] for option in this.options completions.push([option.innerHTML, option.value]) select_options: { completions: completions enable_new_options: false } $.extend(select_options, options) $(this).replaceWith(input) new $.MultiSelect(input, select_options) else if this.tagName.toLowerCase() == "input" and this.type == "text" new $.MultiSelect(this, options) )(jQuery) $.extend String.prototype, { trim: -> this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, '') entitizeHTML: -> this.replace(/</g,'&lt;').replace(/>/g,'&gt;') unentitizeHTML: -> this.replace(/&lt;/g,'<').replace(/&gt;/g,'>') blank: -> this.trim().length == 0 present: -> not @blank() }; RegExp.escape: (str) -> String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
wilkerlucio/jquery-multiselect
bf1f701038f18cd1632af9e8cb7b33140c2495d2
z-index on autocomplete to be over other size things
diff --git a/css/jquery.multiselect.css b/css/jquery.multiselect.css index c7e7bab..31cfa98 100644 --- a/css/jquery.multiselect.css +++ b/css/jquery.multiselect.css @@ -1,32 +1,32 @@ /* TextboxList CSS */ *:first-child+html div.holder { padding-bottom: 2px; } * html div.holder { padding-bottom: 2px; } /* ie7 and below */ div.jquery-multiselect *, div.jquery-multiselect-autocomplete * { font: 11px "Lucida Grande", "Verdana"; } /* DIV holder */ div.jquery-multiselect { width: 500px; margin: 0; border: 1px solid #999; overflow: hidden; height: auto !important; height: 1%; padding: 4px 5px 0; cursor: text;} div.jquery-multiselect a { float: left; margin: 0 5px 4px 0; } div.jquery-multiselect a.bit { text-decoration: none; color: black; } div.jquery-multiselect a.bit:active, div.jquery-multiselect a.bit:focus { outline: none; } div.jquery-multiselect a.bit-box { -moz-border-radius: 6px; -webkit-border-radius: 6px; border-radius: 6px; border: 1px solid #CAD8F3; background: #DEE7F8; padding: 1px 5px 2px; padding-right: 15px; position: relative; cursor: default; } div.jquery-multiselect a.bit-box-focus { border-color: #598BEC; background: #598BEC; color: #fff; } div.jquery-multiselect a.bit-hover { background: #BBCEF1; border: 1px solid #6D95E0; } div.jquery-multiselect a.bit-box a.closebutton { position: absolute; right: 0; top: 5px; display: block; width: 7px; height: 7px; font-size: 1px; background: url('../images/close.gif'); cursor: pointer; } div.jquery-multiselect a.bit-box a.closebutton:hover { background-position: 7px; } div.jquery-multiselect a.bit-box a.closebutton:active { outline: none } div.jquery-multiselect a.bit-input input { width: 150px; margin: 0; border: none; outline: 0; padding: 3px 0 2px; } /* no left/right padding here please */ div.jquery-multiselect a.bit-box-focus a.closebutton, div.jquery-multiselect a.bit-box-focus a.closebutton:hover { background-position: bottom; } /* Autocompleter CSS */ -div.jquery-multiselect-autocomplete { position: absolute; width: 512px; background: #eee; } +div.jquery-multiselect-autocomplete { position: absolute; width: 512px; background: #eee; z-index: 999999; } div.jquery-multiselect-autocomplete .default { padding: 5px 7px; border: 1px solid #ccc; border-width: 0 1px 1px; } div.jquery-multiselect-autocomplete ul { margin: 0; padding: 0; overflow: auto; } div.jquery-multiselect-autocomplete ul li { padding: 5px 12px; z-index: 1000; cursor: pointer; margin: 0; list-style-type: none; border: 1px solid #ccc; border-width: 0 1px 1px; } div.jquery-multiselect-autocomplete ul li em { font-weight: bold; font-style: normal; background: #ccc; } div.jquery-multiselect-autocomplete ul li.auto-focus { background: #4173CC; color: #fff; } div.jquery-multiselect-autocomplete ul li.auto-focus em { background: none; } input.inputMessage { color: #ccc; font-size: 11px; } /* Mine */
wilkerlucio/jquery-multiselect
61b7e179b194f0b59a6642cd8b6e23fd7c2c962c
released 0.1.5
diff --git a/VERSION b/VERSION index 446ba66..def9a01 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.1.4 \ No newline at end of file +0.1.5 \ No newline at end of file diff --git a/dist/jquery.multiselect.0.1.5.min.js b/dist/jquery.multiselect.0.1.5.min.js new file mode 100644 index 0000000..e3127b2 --- /dev/null +++ b/dist/jquery.multiselect.0.1.5.min.js @@ -0,0 +1,33 @@ +/** + * Copyright (c) 2010 Wilker Lúcio + * + * 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. + */ + +(function($){var KEY;KEY={BACKSPACE:8,TAB:9,RETURN:13,ESCAPE:27,SPACE:32,LEFT:37,UP:38,RIGHT:39,DOWN:40,COLON:188,DOT:190};$.MultiSelect=function MultiSelect(element,options){this.options={separator:",",completions:[],max_complete_results:5,enable_new_options:true};$.extend(this.options,options||{});this.values=[];this.input=$(element);this.initialize_elements();this.initialize_events();this.parse_value();return this;};$.MultiSelect.prototype.initialize_elements=function initialize_elements(){this.hidden=$(document.createElement("input"));this.hidden.attr("name",this.input.attr("name"));this.hidden.attr("type","hidden");this.input.removeAttr("name");this.container=$(document.createElement("div"));this.container.addClass("jquery-multiselect");this.input_wrapper=$(document.createElement("a"));this.input_wrapper.addClass("bit-input");this.input.replaceWith(this.container);this.container.append(this.input_wrapper);this.input_wrapper.append(this.input);return this.container.before(this.hidden);};$.MultiSelect.prototype.initialize_events=function initialize_events(){this.selection=new $.MultiSelect.Selection(this.input);this.resizable=new $.MultiSelect.ResizableInput(this.input);this.observer=new $.MultiSelect.InputObserver(this.input);this.autocomplete=new $.MultiSelect.AutoComplete(this,this.options.completions);this.input.click((function(__this){var __func=function(e){return e.stopPropagation();};return(function(){return __func.apply(__this,arguments);});})(this));this.input.keyup((function(__this){var __func=function(){return this.parse_value(1);};return(function(){return __func.apply(__this,arguments);});})(this));this.container.click((function(__this){var __func=function(){this.input.focus();return this.selection.set_caret_at_end();};return(function(){return __func.apply(__this,arguments);});})(this));this.observer.bind([KEY.TAB,KEY.RETURN],(function(__this){var __func=function(e){if(this.autocomplete.val()){e.preventDefault();return this.add_and_reset();}};return(function(){return __func.apply(__this,arguments);});})(this));return this.observer.bind([KEY.BACKSPACE],(function(__this){var __func=function(e){var caret;if(this.values.length<=0){return null;} +caret=this.selection.get_caret();if(caret[0]===0&&caret[1]===0){e.preventDefault();return this.remove(this.values[this.values.length-1]);}};return(function(){return __func.apply(__this,arguments);});})(this));};$.MultiSelect.prototype.values_real=function values_real(){return $.map(this.values,function(v){return v[1];});};$.MultiSelect.prototype.parse_value=function parse_value(min){var _a,_b,_c,value,values;min=(typeof min!=="undefined"&&min!==null)?min:0;values=this.input.val().split(this.options.separator);if(values.length>min){_b=values;for(_a=0,_c=_b.length;_a<_c;_a++){value=_b[_a];if(value.present()){this.add([value,value]);}} +this.input.val("");return this.autocomplete.search();}};$.MultiSelect.prototype.add_and_reset=function add_and_reset(){if(this.autocomplete.val()){this.add(this.autocomplete.val());this.input.val("");return this.autocomplete.search();}};$.MultiSelect.prototype.add=function add(value){var a,close;if($.inArray(value[1],this.values_real())>-1){return null;} +if(value[0].blank()){return null;} +value[1]=value[1].trim();this.values.push(value);a=$(document.createElement("a"));a.addClass("bit bit-box");a.mouseover(function(){return $(this).addClass("bit-hover");});a.mouseout(function(){return $(this).removeClass("bit-hover");});a.data("value",value);a.html(value[0].entitizeHTML());close=$(document.createElement("a"));close.addClass("closebutton");close.click((function(__this){var __func=function(){return this.remove(a.data("value"));};return(function(){return __func.apply(__this,arguments);});})(this));a.append(close);this.input_wrapper.before(a);return this.refresh_hidden();};$.MultiSelect.prototype.remove=function remove(value){this.values=$.grep(this.values,function(v){return v[1]!==value[1];});this.container.find("a.bit-box").each(function(){if($(this).data("value")[1]===value[1]){return $(this).remove();}});return this.refresh_hidden();};$.MultiSelect.prototype.refresh_hidden=function refresh_hidden(){return this.hidden.val(this.values_real().join(this.options.separator));};$.MultiSelect.InputObserver=function InputObserver(element){this.input=$(element);this.input.keydown((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.handle_keydown,this,[])));this.events=[];return this;};$.MultiSelect.InputObserver.prototype.bind=function bind(key,callback){return this.events.push([key,callback]);};$.MultiSelect.InputObserver.prototype.handle_keydown=function handle_keydown(e){var _a,_b,_c,_d,_e,callback,event,keys;_a=[];_c=this.events;for(_b=0,_d=_c.length;_b<_d;_b++){event=_c[_b];_a.push((function(){_e=event;keys=_e[0];callback=_e[1];if(!(keys.push)){keys=[keys];} +if($.inArray(e.keyCode,keys)>-1){return callback(e);}}).call(this));} +return _a;};$.MultiSelect.Selection=function Selection(element){this.input=$(element)[0];return this;};$.MultiSelect.Selection.prototype.get_caret=function get_caret(){var r;if(document.selection){r=document.selection.createRange().duplicate();r.moveEnd('character',this.input.value.length);if(r.text===''){return[this.input.value.length,this.input.value.length];}else{return[this.input.value.lastIndexOf(r.text),this.input.value.lastIndexOf(r.text)];}}else{return[this.input.selectionStart,this.input.selectionEnd];}};$.MultiSelect.Selection.prototype.set_caret=function set_caret(begin,end){end=(typeof end!=="undefined"&&end!==null)?end:begin;this.input.selectionStart=begin;this.input.selectionEnd=end;return this.input.selectionEnd;};$.MultiSelect.Selection.prototype.set_caret_at_end=function set_caret_at_end(){return this.set_caret(this.input.value.length);};$.MultiSelect.ResizableInput=function ResizableInput(element){this.input=$(element);this.create_measurer();this.input.keypress((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.set_width,this,[])));this.input.keyup((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.set_width,this,[])));this.input.change((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.set_width,this,[])));return this;};$.MultiSelect.ResizableInput.prototype.create_measurer=function create_measurer(){var measurer;if($("#__jquery_multiselect_measurer")[0]===undefined){measurer=$(document.createElement("div"));measurer.attr("id","__jquery_multiselect_measurer");measurer.css({position:"absolute",left:"-1000px",top:"-1000px"});$(document.body).append(measurer);} +this.measurer=$("#__jquery_multiselect_measurer:first");return this.measurer.css({fontSize:this.input.css('font-size'),fontFamily:this.input.css('font-family')});};$.MultiSelect.ResizableInput.prototype.calculate_width=function calculate_width(){this.measurer.html(this.input.val().entitizeHTML()+'MM');return this.measurer.innerWidth();};$.MultiSelect.ResizableInput.prototype.set_width=function set_width(){return this.input.css("width",this.calculate_width()+"px");};$.MultiSelect.AutoComplete=function AutoComplete(multiselect,completions){this.multiselect=multiselect;this.input=this.multiselect.input;this.completions=this.parse_completions(completions);this.matches=[];this.create_elements();this.bind_events();return this;};$.MultiSelect.AutoComplete.prototype.parse_completions=function parse_completions(completions){return $.map(completions,function(value){if(typeof value==="string"){return[[value,value]];}else if(value instanceof Array&&value.length===2){return[value];}else if(value.value&&value.caption){return[[value.caption,value.value]];}else if(console){return console.error("Invalid option "+(value));}});};$.MultiSelect.AutoComplete.prototype.create_elements=function create_elements(){this.container=$(document.createElement("div"));this.container.addClass("jquery-multiselect-autocomplete");this.container.css("width",this.multiselect.container.outerWidth());this.container.css("display","none");this.container.append(this.def);this.list=$(document.createElement("ul"));this.list.addClass("feed");this.container.append(this.list);return this.multiselect.container.after(this.container);};$.MultiSelect.AutoComplete.prototype.bind_events=function bind_events(){this.input.keypress((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.search,this,[])));this.input.keyup((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.search,this,[])));this.input.change((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.search,this,[])));this.multiselect.observer.bind(KEY.UP,(function(__this){var __func=function(e){e.preventDefault();return this.navigate_up();};return(function(){return __func.apply(__this,arguments);});})(this));return this.multiselect.observer.bind(KEY.DOWN,(function(__this){var __func=function(e){e.preventDefault();return this.navigate_down();};return(function(){return __func.apply(__this,arguments);});})(this));};$.MultiSelect.AutoComplete.prototype.search=function search(){var _a,_b,def,i,item,option,x;if(this.input.val().trim()===this.query){return null;} +this.query=this.input.val().trim();this.list.html("");this.current=0;if(this.query.present()){this.container.css("display","block");this.matches=this.matching_completions(this.query);if(this.multiselect.options.enable_new_options){def=this.create_item("Add <em>"+this.query+"</em>");def.mouseover((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.select_index,this,[0])));} +_a=this.matches;for(i=0,_b=_a.length;i<_b;i++){option=_a[i];x=this.multiselect.options.enable_new_options?i+1:i;item=this.create_item(this.highlight(option[0],this.query));item.mouseover((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.select_index,this,[x])));} +if(this.multiselect.options.enable_new_options){this.matches.unshift([this.query,this.query]);} +return this.select_index(0);}else{this.matches=[];this.container.css("display","none");this.query=null;return this.query;}};$.MultiSelect.AutoComplete.prototype.select_index=function select_index(index){var items;items=this.list.find("li");items.removeClass("auto-focus");items.filter(":eq("+(index)+")").addClass("auto-focus");this.current=index;return this.current;};$.MultiSelect.AutoComplete.prototype.navigate_down=function navigate_down(){var next;next=this.current+1;if(next>=this.matches.length){next=0;} +return this.select_index(next);};$.MultiSelect.AutoComplete.prototype.navigate_up=function navigate_up(){var next;next=this.current-1;if(next<0){next=this.matches.length-1;} +return this.select_index(next);};$.MultiSelect.AutoComplete.prototype.create_item=function create_item(text,highlight){var item;item=$(document.createElement("li"));item.click((function(__this){var __func=function(){this.multiselect.add_and_reset();this.search();return this.input.focus();};return(function(){return __func.apply(__this,arguments);});})(this));item.html(text);this.list.append(item);return item;};$.MultiSelect.AutoComplete.prototype.val=function val(){return this.matches[this.current];};$.MultiSelect.AutoComplete.prototype.highlight=function highlight(text,highlight){var reg;reg="("+(RegExp.escape(highlight))+")";return text.replace(new RegExp(reg,"gi"),'<em>$1</em>');};$.MultiSelect.AutoComplete.prototype.matching_completions=function matching_completions(text){var count,reg;reg=new RegExp(RegExp.escape(text),"i");count=0;return $.grep(this.completions,(function(__this){var __func=function(c){if(count>=this.multiselect.options.max_complete_results){return false;} +if($.inArray(c[1],this.multiselect.values_real())>-1){return false;} +if(c[0].match(reg)){count++;return true;}else{return false;}};return(function(){return __func.apply(__this,arguments);});})(this));};$.fn.multiselect=function multiselect(options){options=(typeof options!=="undefined"&&options!==null)?options:{};return $(this).each(function(){var _a,_b,_c,completions,input,option,select_options;if(this.tagName.toLowerCase()==="select"){input=$(document.createElement("input"));input.attr("type","text");input.attr("name",this.name);input.attr("id",this.id);completions=[];_b=this.options;for(_a=0,_c=_b.length;_a<_c;_a++){option=_b[_a];completions.push([option.innerHTML,option.value]);} +select_options={completions:completions,enable_new_options:false};$.extend(select_options,options);$(this).replaceWith(input);return new $.MultiSelect(input,select_options);}else if(this.tagName.toLowerCase()==="input"&&this.type==="text"){return new $.MultiSelect(this,options);}});};return $.fn.multiselect;})(jQuery);$.extend(String.prototype,{trim:function trim(){return this.replace(/^[\r\n\s]/g,'').replace(/[\r\n\s]$/g,'');},entitizeHTML:function entitizeHTML(){return this.replace(/</g,'&lt;').replace(/>/g,'&gt;');},unentitizeHTML:function unentitizeHTML(){return this.replace(/&lt;/g,'<').replace(/&gt;/g,'>');},blank:function blank(){return this.trim().length===0;},present:function present(){return!this.blank();}});RegExp.escape=function escape(str){return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g,'\\$1');}; \ No newline at end of file
wilkerlucio/jquery-multiselect
9e39c9295df9eec9bb8c3138daa21b5e6b0b353b
fixed cursor when enable_new_options is false
diff --git a/js/jquery.multiselect.js b/js/jquery.multiselect.js index e536005..fecfe2a 100644 --- a/js/jquery.multiselect.js +++ b/js/jquery.multiselect.js @@ -1,541 +1,542 @@ // Copyright (c) 2010 Wilker Lúcio // // 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. (function($) { var KEY; KEY = { BACKSPACE: 8, TAB: 9, RETURN: 13, ESCAPE: 27, SPACE: 32, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, COLON: 188, DOT: 190 }; $.MultiSelect = function MultiSelect(element, options) { this.options = { separator: ",", completions: [], max_complete_results: 5, enable_new_options: true }; $.extend(this.options, options || {}); this.values = []; this.input = $(element); this.initialize_elements(); this.initialize_events(); this.parse_value(); return this; }; $.MultiSelect.prototype.initialize_elements = function initialize_elements() { // hidden input to hold real value this.hidden = $(document.createElement("input")); this.hidden.attr("name", this.input.attr("name")); this.hidden.attr("type", "hidden"); this.input.removeAttr("name"); this.container = $(document.createElement("div")); this.container.addClass("jquery-multiselect"); this.input_wrapper = $(document.createElement("a")); this.input_wrapper.addClass("bit-input"); this.input.replaceWith(this.container); this.container.append(this.input_wrapper); this.input_wrapper.append(this.input); return this.container.before(this.hidden); }; $.MultiSelect.prototype.initialize_events = function initialize_events() { // create helpers this.selection = new $.MultiSelect.Selection(this.input); this.resizable = new $.MultiSelect.ResizableInput(this.input); this.observer = new $.MultiSelect.InputObserver(this.input); this.autocomplete = new $.MultiSelect.AutoComplete(this, this.options.completions); // prevent container click to put carret at end this.input.click((function(__this) { var __func = function(e) { return e.stopPropagation(); }; return (function() { return __func.apply(__this, arguments); }); })(this)); // create element when place separator or paste this.input.keyup((function(__this) { var __func = function() { return this.parse_value(1); }; return (function() { return __func.apply(__this, arguments); }); })(this)); // focus input and set carret at and this.container.click((function(__this) { var __func = function() { this.input.focus(); return this.selection.set_caret_at_end(); }; return (function() { return __func.apply(__this, arguments); }); })(this)); // add element on press TAB or RETURN this.observer.bind([KEY.TAB, KEY.RETURN], (function(__this) { var __func = function(e) { if (this.autocomplete.val()) { e.preventDefault(); return this.add_and_reset(); } }; return (function() { return __func.apply(__this, arguments); }); })(this)); return this.observer.bind([KEY.BACKSPACE], (function(__this) { var __func = function(e) { var caret; if (this.values.length <= 0) { return null; } caret = this.selection.get_caret(); if (caret[0] === 0 && caret[1] === 0) { e.preventDefault(); return this.remove(this.values[this.values.length - 1]); } }; return (function() { return __func.apply(__this, arguments); }); })(this)); }; $.MultiSelect.prototype.values_real = function values_real() { return $.map(this.values, function(v) { return v[1]; }); }; $.MultiSelect.prototype.parse_value = function parse_value(min) { var _a, _b, _c, value, values; min = (typeof min !== "undefined" && min !== null) ? min : 0; values = this.input.val().split(this.options.separator); if (values.length > min) { _b = values; for (_a = 0, _c = _b.length; _a < _c; _a++) { value = _b[_a]; if (value.present()) { this.add([value, value]); } } this.input.val(""); return this.autocomplete.search(); } }; $.MultiSelect.prototype.add_and_reset = function add_and_reset() { if (this.autocomplete.val()) { this.add(this.autocomplete.val()); this.input.val(""); return this.autocomplete.search(); } }; // add new element $.MultiSelect.prototype.add = function add(value) { var a, close; if ($.inArray(value[1], this.values_real()) > -1) { return null; } if (value[0].blank()) { return null; } value[1] = value[1].trim(); this.values.push(value); a = $(document.createElement("a")); a.addClass("bit bit-box"); a.mouseover(function() { return $(this).addClass("bit-hover"); }); a.mouseout(function() { return $(this).removeClass("bit-hover"); }); a.data("value", value); a.html(value[0].entitizeHTML()); close = $(document.createElement("a")); close.addClass("closebutton"); close.click((function(__this) { var __func = function() { return this.remove(a.data("value")); }; return (function() { return __func.apply(__this, arguments); }); })(this)); a.append(close); this.input_wrapper.before(a); return this.refresh_hidden(); }; $.MultiSelect.prototype.remove = function remove(value) { this.values = $.grep(this.values, function(v) { return v[1] !== value[1]; }); this.container.find("a.bit-box").each(function() { if ($(this).data("value")[1] === value[1]) { return $(this).remove(); } }); return this.refresh_hidden(); }; $.MultiSelect.prototype.refresh_hidden = function refresh_hidden() { return this.hidden.val(this.values_real().join(this.options.separator)); }; // Input Observer Helper $.MultiSelect.InputObserver = function InputObserver(element) { this.input = $(element); this.input.keydown((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.handle_keydown, this, []))); this.events = []; return this; }; $.MultiSelect.InputObserver.prototype.bind = function bind(key, callback) { return this.events.push([key, callback]); }; $.MultiSelect.InputObserver.prototype.handle_keydown = function handle_keydown(e) { var _a, _b, _c, _d, _e, callback, event, keys; _a = []; _c = this.events; for (_b = 0, _d = _c.length; _b < _d; _b++) { event = _c[_b]; _a.push((function() { _e = event; keys = _e[0]; callback = _e[1]; if (!(keys.push)) { keys = [keys]; } if ($.inArray(e.keyCode, keys) > -1) { return callback(e); } }).call(this)); } return _a; }; // Selection Helper $.MultiSelect.Selection = function Selection(element) { this.input = $(element)[0]; return this; }; $.MultiSelect.Selection.prototype.get_caret = function get_caret() { var r; // For IE if (document.selection) { r = document.selection.createRange().duplicate(); r.moveEnd('character', this.input.value.length); if (r.text === '') { return [this.input.value.length, this.input.value.length]; } else { return [this.input.value.lastIndexOf(r.text), this.input.value.lastIndexOf(r.text)]; // Others } } else { return [this.input.selectionStart, this.input.selectionEnd]; } }; $.MultiSelect.Selection.prototype.set_caret = function set_caret(begin, end) { end = (typeof end !== "undefined" && end !== null) ? end : begin; this.input.selectionStart = begin; this.input.selectionEnd = end; return this.input.selectionEnd; }; $.MultiSelect.Selection.prototype.set_caret_at_end = function set_caret_at_end() { return this.set_caret(this.input.value.length); }; // Resizable Input Helper $.MultiSelect.ResizableInput = function ResizableInput(element) { this.input = $(element); this.create_measurer(); this.input.keypress((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.set_width, this, []))); this.input.keyup((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.set_width, this, []))); this.input.change((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.set_width, this, []))); return this; }; $.MultiSelect.ResizableInput.prototype.create_measurer = function create_measurer() { var measurer; if ($("#__jquery_multiselect_measurer")[0] === undefined) { measurer = $(document.createElement("div")); measurer.attr("id", "__jquery_multiselect_measurer"); measurer.css({ position: "absolute", left: "-1000px", top: "-1000px" }); $(document.body).append(measurer); } this.measurer = $("#__jquery_multiselect_measurer:first"); return this.measurer.css({ fontSize: this.input.css('font-size'), fontFamily: this.input.css('font-family') }); }; $.MultiSelect.ResizableInput.prototype.calculate_width = function calculate_width() { this.measurer.html(this.input.val().entitizeHTML() + 'MM'); return this.measurer.innerWidth(); }; $.MultiSelect.ResizableInput.prototype.set_width = function set_width() { return this.input.css("width", this.calculate_width() + "px"); }; // AutoComplete Helper $.MultiSelect.AutoComplete = function AutoComplete(multiselect, completions) { this.multiselect = multiselect; this.input = this.multiselect.input; this.completions = this.parse_completions(completions); this.matches = []; this.create_elements(); this.bind_events(); return this; }; $.MultiSelect.AutoComplete.prototype.parse_completions = function parse_completions(completions) { return $.map(completions, function(value) { if (typeof value === "string") { return [[value, value]]; } else if (value instanceof Array && value.length === 2) { return [value]; } else if (value.value && value.caption) { return [[value.caption, value.value]]; } else if (console) { return console.error("Invalid option " + (value)); } }); }; $.MultiSelect.AutoComplete.prototype.create_elements = function create_elements() { this.container = $(document.createElement("div")); this.container.addClass("jquery-multiselect-autocomplete"); this.container.css("width", this.multiselect.container.outerWidth()); this.container.css("display", "none"); this.container.append(this.def); this.list = $(document.createElement("ul")); this.list.addClass("feed"); this.container.append(this.list); return this.multiselect.container.after(this.container); }; $.MultiSelect.AutoComplete.prototype.bind_events = function bind_events() { this.input.keypress((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.search, this, []))); this.input.keyup((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.search, this, []))); this.input.change((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.search, this, []))); this.multiselect.observer.bind(KEY.UP, (function(__this) { var __func = function(e) { e.preventDefault(); return this.navigate_up(); }; return (function() { return __func.apply(__this, arguments); }); })(this)); return this.multiselect.observer.bind(KEY.DOWN, (function(__this) { var __func = function(e) { e.preventDefault(); return this.navigate_down(); }; return (function() { return __func.apply(__this, arguments); }); })(this)); }; $.MultiSelect.AutoComplete.prototype.search = function search() { - var _a, _b, def, i, item, option; + var _a, _b, def, i, item, option, x; if (this.input.val().trim() === this.query) { return null; } // dont do operation if query is same this.query = this.input.val().trim(); this.list.html(""); // clear list this.current = 0; if (this.query.present()) { this.container.css("display", "block"); this.matches = this.matching_completions(this.query); if (this.multiselect.options.enable_new_options) { def = this.create_item("Add <em>" + this.query + "</em>"); def.mouseover((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.select_index, this, [0]))); } _a = this.matches; for (i = 0, _b = _a.length; i < _b; i++) { option = _a[i]; + x = this.multiselect.options.enable_new_options ? i + 1 : i; item = this.create_item(this.highlight(option[0], this.query)); item.mouseover((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; - }(this.select_index, this, [i + 1]))); + }(this.select_index, this, [x]))); } if (this.multiselect.options.enable_new_options) { this.matches.unshift([this.query, this.query]); } return this.select_index(0); } else { this.matches = []; this.container.css("display", "none"); this.query = null; return this.query; } }; $.MultiSelect.AutoComplete.prototype.select_index = function select_index(index) { var items; items = this.list.find("li"); items.removeClass("auto-focus"); items.filter(":eq(" + (index) + ")").addClass("auto-focus"); this.current = index; return this.current; }; $.MultiSelect.AutoComplete.prototype.navigate_down = function navigate_down() { var next; next = this.current + 1; if (next >= this.matches.length) { next = 0; } return this.select_index(next); }; $.MultiSelect.AutoComplete.prototype.navigate_up = function navigate_up() { var next; next = this.current - 1; if (next < 0) { next = this.matches.length - 1; } return this.select_index(next); }; $.MultiSelect.AutoComplete.prototype.create_item = function create_item(text, highlight) { var item; item = $(document.createElement("li")); item.click((function(__this) { var __func = function() { this.multiselect.add_and_reset(); this.search(); return this.input.focus(); }; return (function() { return __func.apply(__this, arguments); }); })(this)); item.html(text); this.list.append(item); return item; }; $.MultiSelect.AutoComplete.prototype.val = function val() { return this.matches[this.current]; }; $.MultiSelect.AutoComplete.prototype.highlight = function highlight(text, highlight) { var reg; reg = "(" + (RegExp.escape(highlight)) + ")"; return text.replace(new RegExp(reg, "gi"), '<em>$1</em>'); }; $.MultiSelect.AutoComplete.prototype.matching_completions = function matching_completions(text) { var count, reg; reg = new RegExp(RegExp.escape(text), "i"); count = 0; return $.grep(this.completions, (function(__this) { var __func = function(c) { if (count >= this.multiselect.options.max_complete_results) { return false; } if ($.inArray(c[1], this.multiselect.values_real()) > -1) { return false; } if (c[0].match(reg)) { count++; return true; } else { return false; } }; return (function() { return __func.apply(__this, arguments); }); })(this)); }; // Hook jQuery extension $.fn.multiselect = function multiselect(options) { options = (typeof options !== "undefined" && options !== null) ? options : {}; return $(this).each(function() { var _a, _b, _c, completions, input, option, select_options; if (this.tagName.toLowerCase() === "select") { input = $(document.createElement("input")); input.attr("type", "text"); input.attr("name", this.name); input.attr("id", this.id); completions = []; _b = this.options; for (_a = 0, _c = _b.length; _a < _c; _a++) { option = _b[_a]; completions.push([option.innerHTML, option.value]); } select_options = { completions: completions, enable_new_options: false }; $.extend(select_options, options); $(this).replaceWith(input); return new $.MultiSelect(input, select_options); } else if (this.tagName.toLowerCase() === "input" && this.type === "text") { return new $.MultiSelect(this, options); } }); }; return $.fn.multiselect; })(jQuery); $.extend(String.prototype, { trim: function trim() { return this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, ''); }, entitizeHTML: function entitizeHTML() { return this.replace(/</g, '&lt;').replace(/>/g, '&gt;'); }, unentitizeHTML: function unentitizeHTML() { return this.replace(/&lt;/g, '<').replace(/&gt;/g, '>'); }, blank: function blank() { return this.trim().length === 0; }, present: function present() { return !this.blank(); } }); RegExp.escape = function escape(str) { return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); }; \ No newline at end of file diff --git a/src/jquery.multiselect.coffee b/src/jquery.multiselect.coffee index 4106551..6909764 100644 --- a/src/jquery.multiselect.coffee +++ b/src/jquery.multiselect.coffee @@ -1,381 +1,382 @@ # Copyright (c) 2010 Wilker Lúcio # # 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. (($) -> KEY: { BACKSPACE: 8 TAB: 9 RETURN: 13 ESCAPE: 27 SPACE: 32 LEFT: 37 UP: 38 RIGHT: 39 DOWN: 40 COLON: 188 DOT: 190 } class $.MultiSelect constructor: (element, options) -> @options: { separator: "," completions: [] max_complete_results: 5 enable_new_options: true } $.extend(@options, options || {}) @values: [] @input: $(element) @initialize_elements() @initialize_events() @parse_value() initialize_elements: -> # hidden input to hold real value @hidden: $(document.createElement("input")) @hidden.attr("name", @input.attr("name")) @hidden.attr("type", "hidden") @input.removeAttr("name") @container: $(document.createElement("div")) @container.addClass("jquery-multiselect") @input_wrapper: $(document.createElement("a")) @input_wrapper.addClass("bit-input") @input.replaceWith(@container) @container.append(@input_wrapper) @input_wrapper.append(@input) @container.before(@hidden) initialize_events: -> # create helpers @selection: new $.MultiSelect.Selection(@input) @resizable: new $.MultiSelect.ResizableInput(@input) @observer: new $.MultiSelect.InputObserver(@input) @autocomplete: new $.MultiSelect.AutoComplete(this, @options.completions) # prevent container click to put carret at end @input.click (e) => e.stopPropagation() # create element when place separator or paste @input.keyup => @parse_value(1) # focus input and set carret at and @container.click => @input.focus() @selection.set_caret_at_end() # add element on press TAB or RETURN @observer.bind [KEY.TAB, KEY.RETURN], (e) => if @autocomplete.val() e.preventDefault() @add_and_reset() @observer.bind [KEY.BACKSPACE], (e) => return if @values.length <= 0 caret = @selection.get_caret() if caret[0] == 0 and caret[1] == 0 e.preventDefault() @remove(@values[@values.length - 1]) values_real: -> $.map @values, (v) -> v[1] parse_value: (min) -> min ?= 0 values: @input.val().split(@options.separator) if values.length > min for value in values @add [value, value] if value.present() @input.val("") @autocomplete.search() add_and_reset: -> if @autocomplete.val() @add(@autocomplete.val()) @input.val("") @autocomplete.search() # add new element add: (value) -> return if $.inArray(value[1], @values_real()) > -1 return if value[0].blank() value[1] = value[1].trim() @values.push(value) a: $(document.createElement("a")) a.addClass("bit bit-box") a.mouseover -> $(this).addClass("bit-hover") a.mouseout -> $(this).removeClass("bit-hover") a.data("value", value) a.html(value[0].entitizeHTML()) close: $(document.createElement("a")) close.addClass("closebutton") close.click => @remove(a.data("value")) a.append(close) @input_wrapper.before(a) @refresh_hidden() remove: (value) -> @values: $.grep @values, (v) -> v[1] != value[1] @container.find("a.bit-box").each -> $(this).remove() if $(this).data("value")[1] == value[1] @refresh_hidden() refresh_hidden: -> @hidden.val(@values_real().join(@options.separator)) # Input Observer Helper class $.MultiSelect.InputObserver constructor: (element) -> @input: $(element) @input.keydown(@handle_keydown <- this) @events: [] bind: (key, callback) -> @events.push([key, callback]) handle_keydown: (e) -> for event in @events [keys, callback]: event keys: [keys] unless keys.push callback(e) if $.inArray(e.keyCode, keys) > -1 # Selection Helper class $.MultiSelect.Selection constructor: (element) -> @input: $(element)[0] get_caret: -> # For IE if document.selection r: document.selection.createRange().duplicate() r.moveEnd('character', @input.value.length) if r.text == '' [@input.value.length, @input.value.length] else [@input.value.lastIndexOf(r.text), @input.value.lastIndexOf(r.text)] # Others else [@input.selectionStart, @input.selectionEnd] set_caret: (begin, end) -> end ?= begin @input.selectionStart: begin @input.selectionEnd: end set_caret_at_end: -> @set_caret(@input.value.length) # Resizable Input Helper class $.MultiSelect.ResizableInput constructor: (element) -> @input: $(element) @create_measurer() @input.keypress(@set_width <- this) @input.keyup(@set_width <- this) @input.change(@set_width <- this) create_measurer: -> if $("#__jquery_multiselect_measurer")[0] == undefined measurer: $(document.createElement("div")) measurer.attr("id", "__jquery_multiselect_measurer") measurer.css { position: "absolute" left: "-1000px" top: "-1000px" } $(document.body).append(measurer) @measurer: $("#__jquery_multiselect_measurer:first") @measurer.css { fontSize: @input.css('font-size') fontFamily: @input.css('font-family') } calculate_width: -> @measurer.html(@input.val().entitizeHTML() + 'MM') @measurer.innerWidth() set_width: -> @input.css("width", @calculate_width() + "px") # AutoComplete Helper class $.MultiSelect.AutoComplete constructor: (multiselect, completions) -> @multiselect: multiselect @input: @multiselect.input @completions: @parse_completions(completions) @matches: [] @create_elements() @bind_events() parse_completions: (completions) -> $.map completions, (value) -> if typeof value == "string" [[value, value]] else if value instanceof Array and value.length == 2 [value] else if value.value and value.caption [[value.caption, value.value]] else console.error "Invalid option ${value}" if console create_elements: -> @container: $(document.createElement("div")) @container.addClass("jquery-multiselect-autocomplete") @container.css("width", @multiselect.container.outerWidth()) @container.css("display", "none") @container.append(@def) @list: $(document.createElement("ul")) @list.addClass("feed") @container.append(@list) @multiselect.container.after(@container) bind_events: -> @input.keypress(@search <- this) @input.keyup(@search <- this) @input.change(@search <- this) @multiselect.observer.bind KEY.UP, (e) => e.preventDefault(); @navigate_up() @multiselect.observer.bind KEY.DOWN, (e) => e.preventDefault(); @navigate_down() search: -> return if @input.val().trim() == @query # dont do operation if query is same @query: @input.val().trim() @list.html("") # clear list @current: 0 if @query.present() @container.css("display", "block") @matches: @matching_completions(@query) if @multiselect.options.enable_new_options def: @create_item("Add <em>" + @query + "</em>") def.mouseover(@select_index <- this, 0) for option, i in @matches + x: if @multiselect.options.enable_new_options then i + 1 else i item: @create_item(@highlight(option[0], @query)) - item.mouseover(@select_index <- this, i + 1) + item.mouseover(@select_index <- this, x) @matches.unshift([@query, @query]) if @multiselect.options.enable_new_options @select_index(0) else @matches: [] @container.css("display", "none") @query: null select_index: (index) -> items: @list.find("li") items.removeClass("auto-focus") items.filter(":eq(${index})").addClass("auto-focus") @current: index navigate_down: -> next: @current + 1 next: 0 if next >= @matches.length @select_index(next) navigate_up: -> next: @current - 1 next: @matches.length - 1 if next < 0 @select_index(next) create_item: (text, highlight) -> item: $(document.createElement("li")) item.click => @multiselect.add_and_reset() @search() @input.focus() item.html(text) @list.append(item) item val: -> @matches[@current] highlight: (text, highlight) -> reg: "(${RegExp.escape(highlight)})" text.replace(new RegExp(reg, "gi"), '<em>$1</em>') matching_completions: (text) -> reg: new RegExp(RegExp.escape(text), "i") count: 0 $.grep @completions, (c) => return false if count >= @multiselect.options.max_complete_results return false if $.inArray(c[1], @multiselect.values_real()) > -1 if c[0].match(reg) count++ true else false # Hook jQuery extension $.fn.multiselect: (options) -> options ?= {} $(this).each -> if this.tagName.toLowerCase() == "select" input: $(document.createElement("input")) input.attr("type", "text") input.attr("name", this.name) input.attr("id", this.id) completions: [] for option in this.options completions.push([option.innerHTML, option.value]) select_options: { completions: completions enable_new_options: false } $.extend(select_options, options) $(this).replaceWith(input) new $.MultiSelect(input, select_options) else if this.tagName.toLowerCase() == "input" and this.type == "text" new $.MultiSelect(this, options) )(jQuery) $.extend String.prototype, { trim: -> this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, '') entitizeHTML: -> this.replace(/</g,'&lt;').replace(/>/g,'&gt;') unentitizeHTML: -> this.replace(/&lt;/g,'<').replace(/&gt;/g,'>') blank: -> this.trim().length == 0 present: -> not @blank() }; RegExp.escape: (str) -> String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
wilkerlucio/jquery-multiselect
0293ab731165775054325e798fb155b1c1f18ef0
release 0.1.4 [removed console request]
diff --git a/VERSION b/VERSION index 7693c96..446ba66 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.1.3 \ No newline at end of file +0.1.4 \ No newline at end of file diff --git a/dist/jquery.multiselect.0.1.4.min.js b/dist/jquery.multiselect.0.1.4.min.js new file mode 100644 index 0000000..af3528a --- /dev/null +++ b/dist/jquery.multiselect.0.1.4.min.js @@ -0,0 +1,33 @@ +/** + * Copyright (c) 2010 Wilker Lúcio + * + * 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. + */ + +(function($){var KEY;KEY={BACKSPACE:8,TAB:9,RETURN:13,ESCAPE:27,SPACE:32,LEFT:37,UP:38,RIGHT:39,DOWN:40,COLON:188,DOT:190};$.MultiSelect=function MultiSelect(element,options){this.options={separator:",",completions:[],max_complete_results:5,enable_new_options:true};$.extend(this.options,options||{});this.values=[];this.input=$(element);this.initialize_elements();this.initialize_events();this.parse_value();return this;};$.MultiSelect.prototype.initialize_elements=function initialize_elements(){this.hidden=$(document.createElement("input"));this.hidden.attr("name",this.input.attr("name"));this.hidden.attr("type","hidden");this.input.removeAttr("name");this.container=$(document.createElement("div"));this.container.addClass("jquery-multiselect");this.input_wrapper=$(document.createElement("a"));this.input_wrapper.addClass("bit-input");this.input.replaceWith(this.container);this.container.append(this.input_wrapper);this.input_wrapper.append(this.input);return this.container.before(this.hidden);};$.MultiSelect.prototype.initialize_events=function initialize_events(){this.selection=new $.MultiSelect.Selection(this.input);this.resizable=new $.MultiSelect.ResizableInput(this.input);this.observer=new $.MultiSelect.InputObserver(this.input);this.autocomplete=new $.MultiSelect.AutoComplete(this,this.options.completions);this.input.click((function(__this){var __func=function(e){return e.stopPropagation();};return(function(){return __func.apply(__this,arguments);});})(this));this.input.keyup((function(__this){var __func=function(){return this.parse_value(1);};return(function(){return __func.apply(__this,arguments);});})(this));this.container.click((function(__this){var __func=function(){this.input.focus();return this.selection.set_caret_at_end();};return(function(){return __func.apply(__this,arguments);});})(this));this.observer.bind([KEY.TAB,KEY.RETURN],(function(__this){var __func=function(e){if(this.autocomplete.val()){e.preventDefault();return this.add_and_reset();}};return(function(){return __func.apply(__this,arguments);});})(this));return this.observer.bind([KEY.BACKSPACE],(function(__this){var __func=function(e){var caret;if(this.values.length<=0){return null;} +caret=this.selection.get_caret();if(caret[0]===0&&caret[1]===0){e.preventDefault();return this.remove(this.values[this.values.length-1]);}};return(function(){return __func.apply(__this,arguments);});})(this));};$.MultiSelect.prototype.values_real=function values_real(){return $.map(this.values,function(v){return v[1];});};$.MultiSelect.prototype.parse_value=function parse_value(min){var _a,_b,_c,value,values;min=(typeof min!=="undefined"&&min!==null)?min:0;values=this.input.val().split(this.options.separator);if(values.length>min){_b=values;for(_a=0,_c=_b.length;_a<_c;_a++){value=_b[_a];if(value.present()){this.add([value,value]);}} +this.input.val("");return this.autocomplete.search();}};$.MultiSelect.prototype.add_and_reset=function add_and_reset(){if(this.autocomplete.val()){this.add(this.autocomplete.val());this.input.val("");return this.autocomplete.search();}};$.MultiSelect.prototype.add=function add(value){var a,close;if($.inArray(value[1],this.values_real())>-1){return null;} +if(value[0].blank()){return null;} +value[1]=value[1].trim();this.values.push(value);a=$(document.createElement("a"));a.addClass("bit bit-box");a.mouseover(function(){return $(this).addClass("bit-hover");});a.mouseout(function(){return $(this).removeClass("bit-hover");});a.data("value",value);a.html(value[0].entitizeHTML());close=$(document.createElement("a"));close.addClass("closebutton");close.click((function(__this){var __func=function(){return this.remove(a.data("value"));};return(function(){return __func.apply(__this,arguments);});})(this));a.append(close);this.input_wrapper.before(a);return this.refresh_hidden();};$.MultiSelect.prototype.remove=function remove(value){this.values=$.grep(this.values,function(v){return v[1]!==value[1];});this.container.find("a.bit-box").each(function(){if($(this).data("value")[1]===value[1]){return $(this).remove();}});return this.refresh_hidden();};$.MultiSelect.prototype.refresh_hidden=function refresh_hidden(){return this.hidden.val(this.values_real().join(this.options.separator));};$.MultiSelect.InputObserver=function InputObserver(element){this.input=$(element);this.input.keydown((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.handle_keydown,this,[])));this.events=[];return this;};$.MultiSelect.InputObserver.prototype.bind=function bind(key,callback){return this.events.push([key,callback]);};$.MultiSelect.InputObserver.prototype.handle_keydown=function handle_keydown(e){var _a,_b,_c,_d,_e,callback,event,keys;_a=[];_c=this.events;for(_b=0,_d=_c.length;_b<_d;_b++){event=_c[_b];_a.push((function(){_e=event;keys=_e[0];callback=_e[1];if(!(keys.push)){keys=[keys];} +if($.inArray(e.keyCode,keys)>-1){return callback(e);}}).call(this));} +return _a;};$.MultiSelect.Selection=function Selection(element){this.input=$(element)[0];return this;};$.MultiSelect.Selection.prototype.get_caret=function get_caret(){var r;if(document.selection){r=document.selection.createRange().duplicate();r.moveEnd('character',this.input.value.length);if(r.text===''){return[this.input.value.length,this.input.value.length];}else{return[this.input.value.lastIndexOf(r.text),this.input.value.lastIndexOf(r.text)];}}else{return[this.input.selectionStart,this.input.selectionEnd];}};$.MultiSelect.Selection.prototype.set_caret=function set_caret(begin,end){end=(typeof end!=="undefined"&&end!==null)?end:begin;this.input.selectionStart=begin;this.input.selectionEnd=end;return this.input.selectionEnd;};$.MultiSelect.Selection.prototype.set_caret_at_end=function set_caret_at_end(){return this.set_caret(this.input.value.length);};$.MultiSelect.ResizableInput=function ResizableInput(element){this.input=$(element);this.create_measurer();this.input.keypress((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.set_width,this,[])));this.input.keyup((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.set_width,this,[])));this.input.change((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.set_width,this,[])));return this;};$.MultiSelect.ResizableInput.prototype.create_measurer=function create_measurer(){var measurer;if($("#__jquery_multiselect_measurer")[0]===undefined){measurer=$(document.createElement("div"));measurer.attr("id","__jquery_multiselect_measurer");measurer.css({position:"absolute",left:"-1000px",top:"-1000px"});$(document.body).append(measurer);} +this.measurer=$("#__jquery_multiselect_measurer:first");return this.measurer.css({fontSize:this.input.css('font-size'),fontFamily:this.input.css('font-family')});};$.MultiSelect.ResizableInput.prototype.calculate_width=function calculate_width(){this.measurer.html(this.input.val().entitizeHTML()+'MM');return this.measurer.innerWidth();};$.MultiSelect.ResizableInput.prototype.set_width=function set_width(){return this.input.css("width",this.calculate_width()+"px");};$.MultiSelect.AutoComplete=function AutoComplete(multiselect,completions){this.multiselect=multiselect;this.input=this.multiselect.input;this.completions=this.parse_completions(completions);this.matches=[];this.create_elements();this.bind_events();return this;};$.MultiSelect.AutoComplete.prototype.parse_completions=function parse_completions(completions){return $.map(completions,function(value){if(typeof value==="string"){return[[value,value]];}else if(value instanceof Array&&value.length===2){return[value];}else if(value.value&&value.caption){return[[value.caption,value.value]];}else if(console){return console.error("Invalid option "+(value));}});};$.MultiSelect.AutoComplete.prototype.create_elements=function create_elements(){this.container=$(document.createElement("div"));this.container.addClass("jquery-multiselect-autocomplete");this.container.css("width",this.multiselect.container.outerWidth());this.container.css("display","none");this.container.append(this.def);this.list=$(document.createElement("ul"));this.list.addClass("feed");this.container.append(this.list);return this.multiselect.container.after(this.container);};$.MultiSelect.AutoComplete.prototype.bind_events=function bind_events(){this.input.keypress((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.search,this,[])));this.input.keyup((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.search,this,[])));this.input.change((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.search,this,[])));this.multiselect.observer.bind(KEY.UP,(function(__this){var __func=function(e){e.preventDefault();return this.navigate_up();};return(function(){return __func.apply(__this,arguments);});})(this));return this.multiselect.observer.bind(KEY.DOWN,(function(__this){var __func=function(e){e.preventDefault();return this.navigate_down();};return(function(){return __func.apply(__this,arguments);});})(this));};$.MultiSelect.AutoComplete.prototype.search=function search(){var _a,_b,def,i,item,option;if(this.input.val().trim()===this.query){return null;} +this.query=this.input.val().trim();this.list.html("");this.current=0;if(this.query.present()){this.container.css("display","block");this.matches=this.matching_completions(this.query);if(this.multiselect.options.enable_new_options){def=this.create_item("Add <em>"+this.query+"</em>");def.mouseover((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.select_index,this,[0])));} +_a=this.matches;for(i=0,_b=_a.length;i<_b;i++){option=_a[i];item=this.create_item(this.highlight(option[0],this.query));item.mouseover((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.select_index,this,[i+1])));} +if(this.multiselect.options.enable_new_options){this.matches.unshift([this.query,this.query]);} +return this.select_index(0);}else{this.matches=[];this.container.css("display","none");this.query=null;return this.query;}};$.MultiSelect.AutoComplete.prototype.select_index=function select_index(index){var items;items=this.list.find("li");items.removeClass("auto-focus");items.filter(":eq("+(index)+")").addClass("auto-focus");this.current=index;return this.current;};$.MultiSelect.AutoComplete.prototype.navigate_down=function navigate_down(){var next;next=this.current+1;if(next>=this.matches.length){next=0;} +return this.select_index(next);};$.MultiSelect.AutoComplete.prototype.navigate_up=function navigate_up(){var next;next=this.current-1;if(next<0){next=this.matches.length-1;} +return this.select_index(next);};$.MultiSelect.AutoComplete.prototype.create_item=function create_item(text,highlight){var item;item=$(document.createElement("li"));item.click((function(__this){var __func=function(){this.multiselect.add_and_reset();this.search();return this.input.focus();};return(function(){return __func.apply(__this,arguments);});})(this));item.html(text);this.list.append(item);return item;};$.MultiSelect.AutoComplete.prototype.val=function val(){return this.matches[this.current];};$.MultiSelect.AutoComplete.prototype.highlight=function highlight(text,highlight){var reg;reg="("+(RegExp.escape(highlight))+")";return text.replace(new RegExp(reg,"gi"),'<em>$1</em>');};$.MultiSelect.AutoComplete.prototype.matching_completions=function matching_completions(text){var count,reg;reg=new RegExp(RegExp.escape(text),"i");count=0;return $.grep(this.completions,(function(__this){var __func=function(c){if(count>=this.multiselect.options.max_complete_results){return false;} +if($.inArray(c[1],this.multiselect.values_real())>-1){return false;} +if(c[0].match(reg)){count++;return true;}else{return false;}};return(function(){return __func.apply(__this,arguments);});})(this));};$.fn.multiselect=function multiselect(options){options=(typeof options!=="undefined"&&options!==null)?options:{};return $(this).each(function(){var _a,_b,_c,completions,input,option,select_options;if(this.tagName.toLowerCase()==="select"){input=$(document.createElement("input"));input.attr("type","text");input.attr("name",this.name);input.attr("id",this.id);completions=[];_b=this.options;for(_a=0,_c=_b.length;_a<_c;_a++){option=_b[_a];completions.push([option.innerHTML,option.value]);} +select_options={completions:completions,enable_new_options:false};$.extend(select_options,options);$(this).replaceWith(input);return new $.MultiSelect(input,select_options);}else if(this.tagName.toLowerCase()==="input"&&this.type==="text"){return new $.MultiSelect(this,options);}});};return $.fn.multiselect;})(jQuery);$.extend(String.prototype,{trim:function trim(){return this.replace(/^[\r\n\s]/g,'').replace(/[\r\n\s]$/g,'');},entitizeHTML:function entitizeHTML(){return this.replace(/</g,'&lt;').replace(/>/g,'&gt;');},unentitizeHTML:function unentitizeHTML(){return this.replace(/&lt;/g,'<').replace(/&gt;/g,'>');},blank:function blank(){return this.trim().length===0;},present:function present(){return!this.blank();}});RegExp.escape=function escape(str){return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g,'\\$1');}; \ No newline at end of file diff --git a/js/jquery.multiselect.js b/js/jquery.multiselect.js index f8157e3..e536005 100644 --- a/js/jquery.multiselect.js +++ b/js/jquery.multiselect.js @@ -1,542 +1,541 @@ // Copyright (c) 2010 Wilker Lúcio // // 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. (function($) { var KEY; KEY = { BACKSPACE: 8, TAB: 9, RETURN: 13, ESCAPE: 27, SPACE: 32, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, COLON: 188, DOT: 190 }; $.MultiSelect = function MultiSelect(element, options) { this.options = { separator: ",", completions: [], max_complete_results: 5, enable_new_options: true }; $.extend(this.options, options || {}); this.values = []; this.input = $(element); this.initialize_elements(); this.initialize_events(); this.parse_value(); return this; }; $.MultiSelect.prototype.initialize_elements = function initialize_elements() { // hidden input to hold real value this.hidden = $(document.createElement("input")); this.hidden.attr("name", this.input.attr("name")); this.hidden.attr("type", "hidden"); this.input.removeAttr("name"); this.container = $(document.createElement("div")); this.container.addClass("jquery-multiselect"); this.input_wrapper = $(document.createElement("a")); this.input_wrapper.addClass("bit-input"); this.input.replaceWith(this.container); this.container.append(this.input_wrapper); this.input_wrapper.append(this.input); return this.container.before(this.hidden); }; $.MultiSelect.prototype.initialize_events = function initialize_events() { // create helpers this.selection = new $.MultiSelect.Selection(this.input); this.resizable = new $.MultiSelect.ResizableInput(this.input); this.observer = new $.MultiSelect.InputObserver(this.input); this.autocomplete = new $.MultiSelect.AutoComplete(this, this.options.completions); // prevent container click to put carret at end this.input.click((function(__this) { var __func = function(e) { return e.stopPropagation(); }; return (function() { return __func.apply(__this, arguments); }); })(this)); // create element when place separator or paste this.input.keyup((function(__this) { var __func = function() { return this.parse_value(1); }; return (function() { return __func.apply(__this, arguments); }); })(this)); // focus input and set carret at and this.container.click((function(__this) { var __func = function() { this.input.focus(); return this.selection.set_caret_at_end(); }; return (function() { return __func.apply(__this, arguments); }); })(this)); // add element on press TAB or RETURN this.observer.bind([KEY.TAB, KEY.RETURN], (function(__this) { var __func = function(e) { if (this.autocomplete.val()) { e.preventDefault(); return this.add_and_reset(); } }; return (function() { return __func.apply(__this, arguments); }); })(this)); return this.observer.bind([KEY.BACKSPACE], (function(__this) { var __func = function(e) { var caret; if (this.values.length <= 0) { return null; } caret = this.selection.get_caret(); if (caret[0] === 0 && caret[1] === 0) { e.preventDefault(); return this.remove(this.values[this.values.length - 1]); } }; return (function() { return __func.apply(__this, arguments); }); })(this)); }; $.MultiSelect.prototype.values_real = function values_real() { return $.map(this.values, function(v) { return v[1]; }); }; $.MultiSelect.prototype.parse_value = function parse_value(min) { var _a, _b, _c, value, values; min = (typeof min !== "undefined" && min !== null) ? min : 0; values = this.input.val().split(this.options.separator); if (values.length > min) { _b = values; for (_a = 0, _c = _b.length; _a < _c; _a++) { value = _b[_a]; if (value.present()) { this.add([value, value]); } } this.input.val(""); return this.autocomplete.search(); } }; $.MultiSelect.prototype.add_and_reset = function add_and_reset() { if (this.autocomplete.val()) { this.add(this.autocomplete.val()); this.input.val(""); return this.autocomplete.search(); } }; // add new element $.MultiSelect.prototype.add = function add(value) { var a, close; if ($.inArray(value[1], this.values_real()) > -1) { return null; } if (value[0].blank()) { return null; } value[1] = value[1].trim(); this.values.push(value); a = $(document.createElement("a")); a.addClass("bit bit-box"); a.mouseover(function() { return $(this).addClass("bit-hover"); }); a.mouseout(function() { return $(this).removeClass("bit-hover"); }); a.data("value", value); a.html(value[0].entitizeHTML()); close = $(document.createElement("a")); close.addClass("closebutton"); close.click((function(__this) { var __func = function() { return this.remove(a.data("value")); }; return (function() { return __func.apply(__this, arguments); }); })(this)); a.append(close); this.input_wrapper.before(a); return this.refresh_hidden(); }; $.MultiSelect.prototype.remove = function remove(value) { - console.log(this.values); this.values = $.grep(this.values, function(v) { return v[1] !== value[1]; }); this.container.find("a.bit-box").each(function() { if ($(this).data("value")[1] === value[1]) { return $(this).remove(); } }); return this.refresh_hidden(); }; $.MultiSelect.prototype.refresh_hidden = function refresh_hidden() { return this.hidden.val(this.values_real().join(this.options.separator)); }; // Input Observer Helper $.MultiSelect.InputObserver = function InputObserver(element) { this.input = $(element); this.input.keydown((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.handle_keydown, this, []))); this.events = []; return this; }; $.MultiSelect.InputObserver.prototype.bind = function bind(key, callback) { return this.events.push([key, callback]); }; $.MultiSelect.InputObserver.prototype.handle_keydown = function handle_keydown(e) { var _a, _b, _c, _d, _e, callback, event, keys; _a = []; _c = this.events; for (_b = 0, _d = _c.length; _b < _d; _b++) { event = _c[_b]; _a.push((function() { _e = event; keys = _e[0]; callback = _e[1]; if (!(keys.push)) { keys = [keys]; } if ($.inArray(e.keyCode, keys) > -1) { return callback(e); } }).call(this)); } return _a; }; // Selection Helper $.MultiSelect.Selection = function Selection(element) { this.input = $(element)[0]; return this; }; $.MultiSelect.Selection.prototype.get_caret = function get_caret() { var r; // For IE if (document.selection) { r = document.selection.createRange().duplicate(); r.moveEnd('character', this.input.value.length); if (r.text === '') { return [this.input.value.length, this.input.value.length]; } else { return [this.input.value.lastIndexOf(r.text), this.input.value.lastIndexOf(r.text)]; // Others } } else { return [this.input.selectionStart, this.input.selectionEnd]; } }; $.MultiSelect.Selection.prototype.set_caret = function set_caret(begin, end) { end = (typeof end !== "undefined" && end !== null) ? end : begin; this.input.selectionStart = begin; this.input.selectionEnd = end; return this.input.selectionEnd; }; $.MultiSelect.Selection.prototype.set_caret_at_end = function set_caret_at_end() { return this.set_caret(this.input.value.length); }; // Resizable Input Helper $.MultiSelect.ResizableInput = function ResizableInput(element) { this.input = $(element); this.create_measurer(); this.input.keypress((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.set_width, this, []))); this.input.keyup((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.set_width, this, []))); this.input.change((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.set_width, this, []))); return this; }; $.MultiSelect.ResizableInput.prototype.create_measurer = function create_measurer() { var measurer; if ($("#__jquery_multiselect_measurer")[0] === undefined) { measurer = $(document.createElement("div")); measurer.attr("id", "__jquery_multiselect_measurer"); measurer.css({ position: "absolute", left: "-1000px", top: "-1000px" }); $(document.body).append(measurer); } this.measurer = $("#__jquery_multiselect_measurer:first"); return this.measurer.css({ fontSize: this.input.css('font-size'), fontFamily: this.input.css('font-family') }); }; $.MultiSelect.ResizableInput.prototype.calculate_width = function calculate_width() { this.measurer.html(this.input.val().entitizeHTML() + 'MM'); return this.measurer.innerWidth(); }; $.MultiSelect.ResizableInput.prototype.set_width = function set_width() { return this.input.css("width", this.calculate_width() + "px"); }; // AutoComplete Helper $.MultiSelect.AutoComplete = function AutoComplete(multiselect, completions) { this.multiselect = multiselect; this.input = this.multiselect.input; this.completions = this.parse_completions(completions); this.matches = []; this.create_elements(); this.bind_events(); return this; }; $.MultiSelect.AutoComplete.prototype.parse_completions = function parse_completions(completions) { return $.map(completions, function(value) { if (typeof value === "string") { return [[value, value]]; } else if (value instanceof Array && value.length === 2) { return [value]; } else if (value.value && value.caption) { return [[value.caption, value.value]]; } else if (console) { return console.error("Invalid option " + (value)); } }); }; $.MultiSelect.AutoComplete.prototype.create_elements = function create_elements() { this.container = $(document.createElement("div")); this.container.addClass("jquery-multiselect-autocomplete"); this.container.css("width", this.multiselect.container.outerWidth()); this.container.css("display", "none"); this.container.append(this.def); this.list = $(document.createElement("ul")); this.list.addClass("feed"); this.container.append(this.list); return this.multiselect.container.after(this.container); }; $.MultiSelect.AutoComplete.prototype.bind_events = function bind_events() { this.input.keypress((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.search, this, []))); this.input.keyup((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.search, this, []))); this.input.change((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.search, this, []))); this.multiselect.observer.bind(KEY.UP, (function(__this) { var __func = function(e) { e.preventDefault(); return this.navigate_up(); }; return (function() { return __func.apply(__this, arguments); }); })(this)); return this.multiselect.observer.bind(KEY.DOWN, (function(__this) { var __func = function(e) { e.preventDefault(); return this.navigate_down(); }; return (function() { return __func.apply(__this, arguments); }); })(this)); }; $.MultiSelect.AutoComplete.prototype.search = function search() { var _a, _b, def, i, item, option; if (this.input.val().trim() === this.query) { return null; } // dont do operation if query is same this.query = this.input.val().trim(); this.list.html(""); // clear list this.current = 0; if (this.query.present()) { this.container.css("display", "block"); this.matches = this.matching_completions(this.query); if (this.multiselect.options.enable_new_options) { def = this.create_item("Add <em>" + this.query + "</em>"); def.mouseover((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.select_index, this, [0]))); } _a = this.matches; for (i = 0, _b = _a.length; i < _b; i++) { option = _a[i]; item = this.create_item(this.highlight(option[0], this.query)); item.mouseover((function(func, obj, args) { return function() { return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0))); }; }(this.select_index, this, [i + 1]))); } if (this.multiselect.options.enable_new_options) { this.matches.unshift([this.query, this.query]); } return this.select_index(0); } else { this.matches = []; this.container.css("display", "none"); this.query = null; return this.query; } }; $.MultiSelect.AutoComplete.prototype.select_index = function select_index(index) { var items; items = this.list.find("li"); items.removeClass("auto-focus"); items.filter(":eq(" + (index) + ")").addClass("auto-focus"); this.current = index; return this.current; }; $.MultiSelect.AutoComplete.prototype.navigate_down = function navigate_down() { var next; next = this.current + 1; if (next >= this.matches.length) { next = 0; } return this.select_index(next); }; $.MultiSelect.AutoComplete.prototype.navigate_up = function navigate_up() { var next; next = this.current - 1; if (next < 0) { next = this.matches.length - 1; } return this.select_index(next); }; $.MultiSelect.AutoComplete.prototype.create_item = function create_item(text, highlight) { var item; item = $(document.createElement("li")); item.click((function(__this) { var __func = function() { this.multiselect.add_and_reset(); this.search(); return this.input.focus(); }; return (function() { return __func.apply(__this, arguments); }); })(this)); item.html(text); this.list.append(item); return item; }; $.MultiSelect.AutoComplete.prototype.val = function val() { return this.matches[this.current]; }; $.MultiSelect.AutoComplete.prototype.highlight = function highlight(text, highlight) { var reg; reg = "(" + (RegExp.escape(highlight)) + ")"; return text.replace(new RegExp(reg, "gi"), '<em>$1</em>'); }; $.MultiSelect.AutoComplete.prototype.matching_completions = function matching_completions(text) { var count, reg; reg = new RegExp(RegExp.escape(text), "i"); count = 0; return $.grep(this.completions, (function(__this) { var __func = function(c) { if (count >= this.multiselect.options.max_complete_results) { return false; } if ($.inArray(c[1], this.multiselect.values_real()) > -1) { return false; } if (c[0].match(reg)) { count++; return true; } else { return false; } }; return (function() { return __func.apply(__this, arguments); }); })(this)); }; // Hook jQuery extension $.fn.multiselect = function multiselect(options) { options = (typeof options !== "undefined" && options !== null) ? options : {}; return $(this).each(function() { var _a, _b, _c, completions, input, option, select_options; if (this.tagName.toLowerCase() === "select") { input = $(document.createElement("input")); input.attr("type", "text"); input.attr("name", this.name); input.attr("id", this.id); completions = []; _b = this.options; for (_a = 0, _c = _b.length; _a < _c; _a++) { option = _b[_a]; completions.push([option.innerHTML, option.value]); } select_options = { completions: completions, enable_new_options: false }; $.extend(select_options, options); $(this).replaceWith(input); return new $.MultiSelect(input, select_options); } else if (this.tagName.toLowerCase() === "input" && this.type === "text") { return new $.MultiSelect(this, options); } }); }; return $.fn.multiselect; })(jQuery); $.extend(String.prototype, { trim: function trim() { return this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, ''); }, entitizeHTML: function entitizeHTML() { return this.replace(/</g, '&lt;').replace(/>/g, '&gt;'); }, unentitizeHTML: function unentitizeHTML() { return this.replace(/&lt;/g, '<').replace(/&gt;/g, '>'); }, blank: function blank() { return this.trim().length === 0; }, present: function present() { return !this.blank(); } }); RegExp.escape = function escape(str) { return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); }; \ No newline at end of file diff --git a/src/jquery.multiselect.coffee b/src/jquery.multiselect.coffee index 46adcbc..4106551 100644 --- a/src/jquery.multiselect.coffee +++ b/src/jquery.multiselect.coffee @@ -1,382 +1,381 @@ # Copyright (c) 2010 Wilker Lúcio # # 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. (($) -> KEY: { BACKSPACE: 8 TAB: 9 RETURN: 13 ESCAPE: 27 SPACE: 32 LEFT: 37 UP: 38 RIGHT: 39 DOWN: 40 COLON: 188 DOT: 190 } class $.MultiSelect constructor: (element, options) -> @options: { separator: "," completions: [] max_complete_results: 5 enable_new_options: true } $.extend(@options, options || {}) @values: [] @input: $(element) @initialize_elements() @initialize_events() @parse_value() initialize_elements: -> # hidden input to hold real value @hidden: $(document.createElement("input")) @hidden.attr("name", @input.attr("name")) @hidden.attr("type", "hidden") @input.removeAttr("name") @container: $(document.createElement("div")) @container.addClass("jquery-multiselect") @input_wrapper: $(document.createElement("a")) @input_wrapper.addClass("bit-input") @input.replaceWith(@container) @container.append(@input_wrapper) @input_wrapper.append(@input) @container.before(@hidden) initialize_events: -> # create helpers @selection: new $.MultiSelect.Selection(@input) @resizable: new $.MultiSelect.ResizableInput(@input) @observer: new $.MultiSelect.InputObserver(@input) @autocomplete: new $.MultiSelect.AutoComplete(this, @options.completions) # prevent container click to put carret at end @input.click (e) => e.stopPropagation() # create element when place separator or paste @input.keyup => @parse_value(1) # focus input and set carret at and @container.click => @input.focus() @selection.set_caret_at_end() # add element on press TAB or RETURN @observer.bind [KEY.TAB, KEY.RETURN], (e) => if @autocomplete.val() e.preventDefault() @add_and_reset() @observer.bind [KEY.BACKSPACE], (e) => return if @values.length <= 0 caret = @selection.get_caret() if caret[0] == 0 and caret[1] == 0 e.preventDefault() @remove(@values[@values.length - 1]) values_real: -> $.map @values, (v) -> v[1] parse_value: (min) -> min ?= 0 values: @input.val().split(@options.separator) if values.length > min for value in values @add [value, value] if value.present() @input.val("") @autocomplete.search() add_and_reset: -> if @autocomplete.val() @add(@autocomplete.val()) @input.val("") @autocomplete.search() # add new element add: (value) -> return if $.inArray(value[1], @values_real()) > -1 return if value[0].blank() value[1] = value[1].trim() @values.push(value) a: $(document.createElement("a")) a.addClass("bit bit-box") a.mouseover -> $(this).addClass("bit-hover") a.mouseout -> $(this).removeClass("bit-hover") a.data("value", value) a.html(value[0].entitizeHTML()) close: $(document.createElement("a")) close.addClass("closebutton") close.click => @remove(a.data("value")) a.append(close) @input_wrapper.before(a) @refresh_hidden() remove: (value) -> - console.log @values @values: $.grep @values, (v) -> v[1] != value[1] @container.find("a.bit-box").each -> $(this).remove() if $(this).data("value")[1] == value[1] @refresh_hidden() refresh_hidden: -> @hidden.val(@values_real().join(@options.separator)) # Input Observer Helper class $.MultiSelect.InputObserver constructor: (element) -> @input: $(element) @input.keydown(@handle_keydown <- this) @events: [] bind: (key, callback) -> @events.push([key, callback]) handle_keydown: (e) -> for event in @events [keys, callback]: event keys: [keys] unless keys.push callback(e) if $.inArray(e.keyCode, keys) > -1 # Selection Helper class $.MultiSelect.Selection constructor: (element) -> @input: $(element)[0] get_caret: -> # For IE if document.selection r: document.selection.createRange().duplicate() r.moveEnd('character', @input.value.length) if r.text == '' [@input.value.length, @input.value.length] else [@input.value.lastIndexOf(r.text), @input.value.lastIndexOf(r.text)] # Others else [@input.selectionStart, @input.selectionEnd] set_caret: (begin, end) -> end ?= begin @input.selectionStart: begin @input.selectionEnd: end set_caret_at_end: -> @set_caret(@input.value.length) # Resizable Input Helper class $.MultiSelect.ResizableInput constructor: (element) -> @input: $(element) @create_measurer() @input.keypress(@set_width <- this) @input.keyup(@set_width <- this) @input.change(@set_width <- this) create_measurer: -> if $("#__jquery_multiselect_measurer")[0] == undefined measurer: $(document.createElement("div")) measurer.attr("id", "__jquery_multiselect_measurer") measurer.css { position: "absolute" left: "-1000px" top: "-1000px" } $(document.body).append(measurer) @measurer: $("#__jquery_multiselect_measurer:first") @measurer.css { fontSize: @input.css('font-size') fontFamily: @input.css('font-family') } calculate_width: -> @measurer.html(@input.val().entitizeHTML() + 'MM') @measurer.innerWidth() set_width: -> @input.css("width", @calculate_width() + "px") # AutoComplete Helper class $.MultiSelect.AutoComplete constructor: (multiselect, completions) -> @multiselect: multiselect @input: @multiselect.input @completions: @parse_completions(completions) @matches: [] @create_elements() @bind_events() parse_completions: (completions) -> $.map completions, (value) -> if typeof value == "string" [[value, value]] else if value instanceof Array and value.length == 2 [value] else if value.value and value.caption [[value.caption, value.value]] else console.error "Invalid option ${value}" if console create_elements: -> @container: $(document.createElement("div")) @container.addClass("jquery-multiselect-autocomplete") @container.css("width", @multiselect.container.outerWidth()) @container.css("display", "none") @container.append(@def) @list: $(document.createElement("ul")) @list.addClass("feed") @container.append(@list) @multiselect.container.after(@container) bind_events: -> @input.keypress(@search <- this) @input.keyup(@search <- this) @input.change(@search <- this) @multiselect.observer.bind KEY.UP, (e) => e.preventDefault(); @navigate_up() @multiselect.observer.bind KEY.DOWN, (e) => e.preventDefault(); @navigate_down() search: -> return if @input.val().trim() == @query # dont do operation if query is same @query: @input.val().trim() @list.html("") # clear list @current: 0 if @query.present() @container.css("display", "block") @matches: @matching_completions(@query) if @multiselect.options.enable_new_options def: @create_item("Add <em>" + @query + "</em>") def.mouseover(@select_index <- this, 0) for option, i in @matches item: @create_item(@highlight(option[0], @query)) item.mouseover(@select_index <- this, i + 1) @matches.unshift([@query, @query]) if @multiselect.options.enable_new_options @select_index(0) else @matches: [] @container.css("display", "none") @query: null select_index: (index) -> items: @list.find("li") items.removeClass("auto-focus") items.filter(":eq(${index})").addClass("auto-focus") @current: index navigate_down: -> next: @current + 1 next: 0 if next >= @matches.length @select_index(next) navigate_up: -> next: @current - 1 next: @matches.length - 1 if next < 0 @select_index(next) create_item: (text, highlight) -> item: $(document.createElement("li")) item.click => @multiselect.add_and_reset() @search() @input.focus() item.html(text) @list.append(item) item val: -> @matches[@current] highlight: (text, highlight) -> reg: "(${RegExp.escape(highlight)})" text.replace(new RegExp(reg, "gi"), '<em>$1</em>') matching_completions: (text) -> reg: new RegExp(RegExp.escape(text), "i") count: 0 $.grep @completions, (c) => return false if count >= @multiselect.options.max_complete_results return false if $.inArray(c[1], @multiselect.values_real()) > -1 if c[0].match(reg) count++ true else false # Hook jQuery extension $.fn.multiselect: (options) -> options ?= {} $(this).each -> if this.tagName.toLowerCase() == "select" input: $(document.createElement("input")) input.attr("type", "text") input.attr("name", this.name) input.attr("id", this.id) completions: [] for option in this.options completions.push([option.innerHTML, option.value]) select_options: { completions: completions enable_new_options: false } $.extend(select_options, options) $(this).replaceWith(input) new $.MultiSelect(input, select_options) else if this.tagName.toLowerCase() == "input" and this.type == "text" new $.MultiSelect(this, options) )(jQuery) $.extend String.prototype, { trim: -> this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, '') entitizeHTML: -> this.replace(/</g,'&lt;').replace(/>/g,'&gt;') unentitizeHTML: -> this.replace(/&lt;/g,'<').replace(/&gt;/g,'>') blank: -> this.trim().length == 0 present: -> not @blank() }; RegExp.escape: (str) -> String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
wilkerlucio/jquery-multiselect
085509a615635791e0d9c47adf864e0aaa60292b
release 0.1.3
diff --git a/VERSION b/VERSION index 8294c18..7693c96 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.1.2 \ No newline at end of file +0.1.3 \ No newline at end of file diff --git a/dist/jquery.multiselect.0.1.3.min.js b/dist/jquery.multiselect.0.1.3.min.js new file mode 100644 index 0000000..2e5f669 --- /dev/null +++ b/dist/jquery.multiselect.0.1.3.min.js @@ -0,0 +1,33 @@ +/** + * Copyright (c) 2010 Wilker Lúcio + * + * 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. + */ + +(function($){var KEY;KEY={BACKSPACE:8,TAB:9,RETURN:13,ESCAPE:27,SPACE:32,LEFT:37,UP:38,RIGHT:39,DOWN:40,COLON:188,DOT:190};$.MultiSelect=function MultiSelect(element,options){this.options={separator:",",completions:[],max_complete_results:5,enable_new_options:true};$.extend(this.options,options||{});this.values=[];this.input=$(element);this.initialize_elements();this.initialize_events();this.parse_value();return this;};$.MultiSelect.prototype.initialize_elements=function initialize_elements(){this.hidden=$(document.createElement("input"));this.hidden.attr("name",this.input.attr("name"));this.hidden.attr("type","hidden");this.input.removeAttr("name");this.container=$(document.createElement("div"));this.container.addClass("jquery-multiselect");this.input_wrapper=$(document.createElement("a"));this.input_wrapper.addClass("bit-input");this.input.replaceWith(this.container);this.container.append(this.input_wrapper);this.input_wrapper.append(this.input);return this.container.before(this.hidden);};$.MultiSelect.prototype.initialize_events=function initialize_events(){this.selection=new $.MultiSelect.Selection(this.input);this.resizable=new $.MultiSelect.ResizableInput(this.input);this.observer=new $.MultiSelect.InputObserver(this.input);this.autocomplete=new $.MultiSelect.AutoComplete(this,this.options.completions);this.input.click((function(__this){var __func=function(e){return e.stopPropagation();};return(function(){return __func.apply(__this,arguments);});})(this));this.input.keyup((function(__this){var __func=function(){return this.parse_value(1);};return(function(){return __func.apply(__this,arguments);});})(this));this.container.click((function(__this){var __func=function(){this.input.focus();return this.selection.set_caret_at_end();};return(function(){return __func.apply(__this,arguments);});})(this));this.observer.bind([KEY.TAB,KEY.RETURN],(function(__this){var __func=function(e){if(this.autocomplete.val()){e.preventDefault();return this.add_and_reset();}};return(function(){return __func.apply(__this,arguments);});})(this));return this.observer.bind([KEY.BACKSPACE],(function(__this){var __func=function(e){var caret;if(this.values.length<=0){return null;} +caret=this.selection.get_caret();if(caret[0]===0&&caret[1]===0){e.preventDefault();return this.remove(this.values[this.values.length-1]);}};return(function(){return __func.apply(__this,arguments);});})(this));};$.MultiSelect.prototype.values_real=function values_real(){return $.map(this.values,function(v){return v[1];});};$.MultiSelect.prototype.parse_value=function parse_value(min){var _a,_b,_c,value,values;min=(typeof min!=="undefined"&&min!==null)?min:0;values=this.input.val().split(this.options.separator);if(values.length>min){_b=values;for(_a=0,_c=_b.length;_a<_c;_a++){value=_b[_a];if(value.present()){this.add([value,value]);}} +this.input.val("");return this.autocomplete.search();}};$.MultiSelect.prototype.add_and_reset=function add_and_reset(){if(this.autocomplete.val()){this.add(this.autocomplete.val());this.input.val("");return this.autocomplete.search();}};$.MultiSelect.prototype.add=function add(value){var a,close;if($.inArray(value[1],this.values_real())>-1){return null;} +if(value[0].blank()){return null;} +value[1]=value[1].trim();this.values.push(value);a=$(document.createElement("a"));a.addClass("bit bit-box");a.mouseover(function(){return $(this).addClass("bit-hover");});a.mouseout(function(){return $(this).removeClass("bit-hover");});a.data("value",value);a.html(value[0].entitizeHTML());close=$(document.createElement("a"));close.addClass("closebutton");close.click((function(__this){var __func=function(){return this.remove(a.data("value"));};return(function(){return __func.apply(__this,arguments);});})(this));a.append(close);this.input_wrapper.before(a);return this.refresh_hidden();};$.MultiSelect.prototype.remove=function remove(value){console.log(this.values);this.values=$.grep(this.values,function(v){return v[1]!==value[1];});this.container.find("a.bit-box").each(function(){if($(this).data("value")[1]===value[1]){return $(this).remove();}});return this.refresh_hidden();};$.MultiSelect.prototype.refresh_hidden=function refresh_hidden(){return this.hidden.val(this.values_real().join(this.options.separator));};$.MultiSelect.InputObserver=function InputObserver(element){this.input=$(element);this.input.keydown((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.handle_keydown,this,[])));this.events=[];return this;};$.MultiSelect.InputObserver.prototype.bind=function bind(key,callback){return this.events.push([key,callback]);};$.MultiSelect.InputObserver.prototype.handle_keydown=function handle_keydown(e){var _a,_b,_c,_d,_e,callback,event,keys;_a=[];_c=this.events;for(_b=0,_d=_c.length;_b<_d;_b++){event=_c[_b];_a.push((function(){_e=event;keys=_e[0];callback=_e[1];if(!(keys.push)){keys=[keys];} +if($.inArray(e.keyCode,keys)>-1){return callback(e);}}).call(this));} +return _a;};$.MultiSelect.Selection=function Selection(element){this.input=$(element)[0];return this;};$.MultiSelect.Selection.prototype.get_caret=function get_caret(){var r;if(document.selection){r=document.selection.createRange().duplicate();r.moveEnd('character',this.input.value.length);if(r.text===''){return[this.input.value.length,this.input.value.length];}else{return[this.input.value.lastIndexOf(r.text),this.input.value.lastIndexOf(r.text)];}}else{return[this.input.selectionStart,this.input.selectionEnd];}};$.MultiSelect.Selection.prototype.set_caret=function set_caret(begin,end){end=(typeof end!=="undefined"&&end!==null)?end:begin;this.input.selectionStart=begin;this.input.selectionEnd=end;return this.input.selectionEnd;};$.MultiSelect.Selection.prototype.set_caret_at_end=function set_caret_at_end(){return this.set_caret(this.input.value.length);};$.MultiSelect.ResizableInput=function ResizableInput(element){this.input=$(element);this.create_measurer();this.input.keypress((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.set_width,this,[])));this.input.keyup((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.set_width,this,[])));this.input.change((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.set_width,this,[])));return this;};$.MultiSelect.ResizableInput.prototype.create_measurer=function create_measurer(){var measurer;if($("#__jquery_multiselect_measurer")[0]===undefined){measurer=$(document.createElement("div"));measurer.attr("id","__jquery_multiselect_measurer");measurer.css({position:"absolute",left:"-1000px",top:"-1000px"});$(document.body).append(measurer);} +this.measurer=$("#__jquery_multiselect_measurer:first");return this.measurer.css({fontSize:this.input.css('font-size'),fontFamily:this.input.css('font-family')});};$.MultiSelect.ResizableInput.prototype.calculate_width=function calculate_width(){this.measurer.html(this.input.val().entitizeHTML()+'MM');return this.measurer.innerWidth();};$.MultiSelect.ResizableInput.prototype.set_width=function set_width(){return this.input.css("width",this.calculate_width()+"px");};$.MultiSelect.AutoComplete=function AutoComplete(multiselect,completions){this.multiselect=multiselect;this.input=this.multiselect.input;this.completions=this.parse_completions(completions);this.matches=[];this.create_elements();this.bind_events();return this;};$.MultiSelect.AutoComplete.prototype.parse_completions=function parse_completions(completions){return $.map(completions,function(value){if(typeof value==="string"){return[[value,value]];}else if(value instanceof Array&&value.length===2){return[value];}else if(value.value&&value.caption){return[[value.caption,value.value]];}else if(console){return console.error("Invalid option "+(value));}});};$.MultiSelect.AutoComplete.prototype.create_elements=function create_elements(){this.container=$(document.createElement("div"));this.container.addClass("jquery-multiselect-autocomplete");this.container.css("width",this.multiselect.container.outerWidth());this.container.css("display","none");this.container.append(this.def);this.list=$(document.createElement("ul"));this.list.addClass("feed");this.container.append(this.list);return this.multiselect.container.after(this.container);};$.MultiSelect.AutoComplete.prototype.bind_events=function bind_events(){this.input.keypress((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.search,this,[])));this.input.keyup((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.search,this,[])));this.input.change((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.search,this,[])));this.multiselect.observer.bind(KEY.UP,(function(__this){var __func=function(e){e.preventDefault();return this.navigate_up();};return(function(){return __func.apply(__this,arguments);});})(this));return this.multiselect.observer.bind(KEY.DOWN,(function(__this){var __func=function(e){e.preventDefault();return this.navigate_down();};return(function(){return __func.apply(__this,arguments);});})(this));};$.MultiSelect.AutoComplete.prototype.search=function search(){var _a,_b,def,i,item,option;if(this.input.val().trim()===this.query){return null;} +this.query=this.input.val().trim();this.list.html("");this.current=0;if(this.query.present()){this.container.css("display","block");this.matches=this.matching_completions(this.query);if(this.multiselect.options.enable_new_options){def=this.create_item("Add <em>"+this.query+"</em>");def.mouseover((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.select_index,this,[0])));} +_a=this.matches;for(i=0,_b=_a.length;i<_b;i++){option=_a[i];item=this.create_item(this.highlight(option[0],this.query));item.mouseover((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.select_index,this,[i+1])));} +if(this.multiselect.options.enable_new_options){this.matches.unshift([this.query,this.query]);} +return this.select_index(0);}else{this.matches=[];this.container.css("display","none");this.query=null;return this.query;}};$.MultiSelect.AutoComplete.prototype.select_index=function select_index(index){var items;items=this.list.find("li");items.removeClass("auto-focus");items.filter(":eq("+(index)+")").addClass("auto-focus");this.current=index;return this.current;};$.MultiSelect.AutoComplete.prototype.navigate_down=function navigate_down(){var next;next=this.current+1;if(next>=this.matches.length){next=0;} +return this.select_index(next);};$.MultiSelect.AutoComplete.prototype.navigate_up=function navigate_up(){var next;next=this.current-1;if(next<0){next=this.matches.length-1;} +return this.select_index(next);};$.MultiSelect.AutoComplete.prototype.create_item=function create_item(text,highlight){var item;item=$(document.createElement("li"));item.click((function(__this){var __func=function(){this.multiselect.add_and_reset();this.search();return this.input.focus();};return(function(){return __func.apply(__this,arguments);});})(this));item.html(text);this.list.append(item);return item;};$.MultiSelect.AutoComplete.prototype.val=function val(){return this.matches[this.current];};$.MultiSelect.AutoComplete.prototype.highlight=function highlight(text,highlight){var reg;reg="("+(RegExp.escape(highlight))+")";return text.replace(new RegExp(reg,"gi"),'<em>$1</em>');};$.MultiSelect.AutoComplete.prototype.matching_completions=function matching_completions(text){var count,reg;reg=new RegExp(RegExp.escape(text),"i");count=0;return $.grep(this.completions,(function(__this){var __func=function(c){if(count>=this.multiselect.options.max_complete_results){return false;} +if($.inArray(c[1],this.multiselect.values_real())>-1){return false;} +if(c[0].match(reg)){count++;return true;}else{return false;}};return(function(){return __func.apply(__this,arguments);});})(this));};$.fn.multiselect=function multiselect(options){options=(typeof options!=="undefined"&&options!==null)?options:{};return $(this).each(function(){var _a,_b,_c,completions,input,option,select_options;if(this.tagName.toLowerCase()==="select"){input=$(document.createElement("input"));input.attr("type","text");input.attr("name",this.name);input.attr("id",this.id);completions=[];_b=this.options;for(_a=0,_c=_b.length;_a<_c;_a++){option=_b[_a];completions.push([option.innerHTML,option.value]);} +select_options={completions:completions,enable_new_options:false};$.extend(select_options,options);$(this).replaceWith(input);return new $.MultiSelect(input,select_options);}else if(this.tagName.toLowerCase()==="input"&&this.type==="text"){return new $.MultiSelect(this,options);}});};return $.fn.multiselect;})(jQuery);$.extend(String.prototype,{trim:function trim(){return this.replace(/^[\r\n\s]/g,'').replace(/[\r\n\s]$/g,'');},entitizeHTML:function entitizeHTML(){return this.replace(/</g,'&lt;').replace(/>/g,'&gt;');},unentitizeHTML:function unentitizeHTML(){return this.replace(/&lt;/g,'<').replace(/&gt;/g,'>');},blank:function blank(){return this.trim().length===0;},present:function present(){return!this.blank();}});RegExp.escape=function escape(str){return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g,'\\$1');}; \ No newline at end of file